What is the difference between +[NSThread detachNewThreadSelector:toTarget:withObject:] and -[NSObject performSelectorInBackground:withObject:]?
Asked Answered
T

2

9

They seem to perform a reasonably similar task: launching a new thread that performs that selector quickly and easily. But are there any differences? Maybe with regards to memory management?

Tingle answered 30/6, 2011 at 18:34 Comment(1)
Good question. I was going to say that perfomSelectorInBackground may reuse a thread from a pool (via libdispatch), but the docs says explicitly that it will create a new thread. So yeah, it does seem to do exactly the same thing as the NSThread method...Assiduous
P
4

Both are identical.

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

Planter answered 30/7, 2011 at 13:35 Comment(0)
R
0

I presume they are the same, as - (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg; is defined in NSThread.h in the NSObject (NSThreadPerformAdditions) category. That is nothing conclusive, but that is evidence in that direction.

Raillery answered 3/7, 2011 at 23:47 Comment(1)
I just did a test, neither one sets up an autorelease pool for you.Raillery

© 2022 - 2024 — McMap. All rights reserved.