Objective-C, NSThread detach vs. performSelectorInBackground
What is the differences between these two?
[NSThread detachNewThreadSelector:@selector(method) toTarget:self withObject:nil];
[self performSelectorInBackground:@selector(method) withObject:nil];
I normally use the second method to spawn a new thread. But I was wondering if I call this twice like shown below in a method then what is going to happen? Also I开发者_如何学运维f I have a tabmenu and each menu spawns a thread then which one I should use?
[self performSelectorInBackground:@selector(method1) withObject:nil];
[self performSelectorInBackground:@selector(method2) withObject:nil];
They are identical. Here is the what the official documentation has to say on this topic:
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.”
As for what happens if you do:
[self performSelectorInBackground:@selector(method1) withObject:nil];
[self performSelectorInBackground:@selector(method2) withObject:nil];
...you will spawn two new threads, one of which starts executing at method1
and one of which starts executing at method2
. The threads may execute concurrently (i.e. the second one will not wait for the first one to terminate before it starts executing).
精彩评论