views:

437

answers:

3

I want to be able to call an object's method on a new thread; but, I am confused about how to manage retain counts (or even if it is an issue).

In a non-threaded scenario, I would do this:

MyObject *newObject = [[MyObject alloc] init];
[newObject doSomething];
[newObject release];

In this scenario, everything's fine. However, my question is whether the following threaded version is a problem:

MyObject *newObject = [[MyObject alloc] init];
[NSThread detachNewThreadSelector:@selector(doSomething)
                         toTarget:newObject
                       withObject:nil];
[newObject release];

In this case, do I have to worry about newObject being released while -doSomething is processing? If the answer is yes, then it seems messy to have -doSomething retain self.

Is this an issue? And, if so, what's the correct solution?

A: 

detachNewThreadSelector retains both aTarget (newObject above) and anArgument (nil above) while the thread is executing, then releases them before exiting the thread.

+5  A: 

From the Xcode API docs:

The objects aTarget and anArgument are retained during the execution of the detached thread, then released. The detached thread is exited (using the exit class method) as soon as aTarget has completed executing the aSelector method.

So, the way you have coded it is fine. You can and should release newObject.

DasBoot
+1  A: 

As others have stated, your code is fine since +detachNewThreadSelector:toTarget:withObject: retains the target. However, I should point out a problem in your terminology. You should not worry about 'newObject' being "released" during the thread (The frameworks are free to retain and release any objects as much as they like as long as the calls are balanced), but instead worry about it being "deallocated." Your code will almost certainly release the 'newObject' while the thread is running, but it won't be deallocated.

Mike Abdullah