views:

78

answers:

1

I have a NSDictionary that is passed from the main thread to a second thread which retains, uses, then releases the variable.

What if the main thread autorelease pool is drained while the 2nd thread is still using the variable? Even though I have retained the variable in the 2nd thread, will the main thread's pool know that its still being used?

Thanks.

+2  A: 

The autorelease pool is pretty dumb. It doesn't "know" that any variable is being used. It simply calls release on each autoreleased object. This generally occurs at the end of each iteration of the event loop.

If the autorelease pool is drained before your second thread has a chance to retain it, it will be deallocated. Instead, it's generally a good idea to retain anything that will be used in another thread before starting the thread. You have no way of knowing when the thread will run, so it's best to assume it won't run until after the autorelease pool is drained.

In other words, do something like this:

NSDictionary *dictionary = // Get the autoreleased dictionary... somehow
[NSThread detachNewThreadSelector:@selector(myThread:) toTarget:self withObject:[dictionary retain]];

Bear in mind your thread now owns dictionary and is responsible for calling release on it before the thread exits, or else your app will leak memory.

Alex