当我多次调用performSelectorInBackground时,作业是否会在同一个线程上排队? 所以首先要先执行,依此类推?
或者,它会在单独的线程中运行吗?
谢谢
答案 0 :(得分:1)
每次调用-performSelectorInBackground:withObject:
Using NSObject to Spawn a Thread
In iOS and Mac OS X v10.5 and later, all objects have the ability to spawn a new thread and use it to execute one of their methods. The performSelectorInBackground:withObject: method creates a new detached thread and uses the specified method as the entry point for the new thread. For example, if you have some object (represented by the variable myObj) and that object has a method called doSomething that you want to run in a background thread, you could could use the following code to do that:
[myObj performSelectorInBackground:@selector(doSomething) withObject:nil];
The effect of calling this method is the same as if you called the detachNewThreadSelector:toTarget:withObject: method of NSThread with the current object, selector, and parameter object as parameters. The new thread is spawned immediately using the default configuration and begins running. Inside the selector, you must configure the thread just as you would any thread. For example, you would need to set up an autorelease pool (if you were not using garbage collection) and configure the thread’s run loop if you planned to use it. For information on how to configure new threads, see “Configuring Thread Attributes.”
答案 1 :(得分:0)
它们将在同一时间执行,而不是一个接一个地执行, 试着这个想法:
-(void)prova1{
for (int i = 1; i<=10000; i++) {
NSLog(@"prova UNO:%i", i);
}
}
-(void)prova2{
for (int i = 1; i<=10000; i++) {
NSLog(@"_________prova DUE:%i", i);
}
}
SEL mioMetodo = NSSelectorFromString(@"prova1");
[self performSelectorInBackground:mioMetodo withObject:nil];
SEL mioMetodo2 = NSSelectorFromString(@"prova2");
[self performSelectorInBackground:mioMetodo2 withObject:nil];
你会得到:
...
_ _ _prova DUE:795
prova UNO:798
_ _ _prova DUE:796
prova UNO:799
_ _ _prova DUE:797
prova UNO:800
_ _ _prova DUE:798
prova UNO:801
_ _ _prova DUE:799
prova UNO:802
_ _ _prova DUE:800
prova UNO:803
_ _ _prova DUE:801
...
如果你想要一个接着一个方法的队列,尝试将2个方法添加到NSOperationQueue并将其setMaxConcurrentOperationCount设置为1 ......