开发者

Creating autoreleased objects on separate threads with NSOperationQueue

开发者 https://www.devze.com 2023-02-08 21:28 出处:网络
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. NSOperat

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 opera开发者_运维知识库tions 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!


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消