Creating autoreleased objects on separate threads with NSOperationQueue

498 views Asked by At

This is a general question about autorelease, Cocoa threads and NSOperationQueue.

I am using NSOperationQueue to perform certain API calls, parse the result and return it to the main thread. NSOperationQueue performs these operations on new threads. If I understand correctly every time a new thread is started there is an automatic autorelease pool created around this thread which is released when the thread is finished.

Here is the case that is giving me trouble. I pass an allocated NSArray to NSOperationQueue. During the operation the array gets populated with a bunch of autoreleased objects that get created. Then the array is returned back to the main thread.

  1. Since the autoreleased objects were created on the thread would they be deallocated? As I understand they should not since their ref count is 1, after they were added to NSArray.

  2. Who now owns releasing these objects? Did autorelease magically passed responsibility to the main thread autorelease pool.

  3. Would any of this be different if I was creating threads myself rather than using NSOperationQueue?

Thank you!

1

There are 1 answers

3
Joe On BEST ANSWER

NSOperations need to have a NSAutoReleasePool created for them.

-(void)main
{
   NSAutoReleasePool *pool = [[NSAutoReleasePool alloc] init];

   //All NSOperation code here

   [pool drain];
}
  1. No, You would probably get a warning in the console about no auto release pool existing. Adding them to an array will increase the ref count by 1 is true, but without a NSAutoReleasePool the ref count would be too high for proper memory management.
  2. You are responsible for creating the autorelease pool for that thread and draining it. They do not magically get put in the the pool on the main thread if your operation is not running on the main thread.
  3. No each thread you responsible for creating an autorelease pool.