NSAutoreleasePool in NSOperation main?

2020-02-24 12:00发布

The documentation for +[NSThread detachNewThreadSelector:toTarget:withObject:] says:

For non garbage-collected applications, the method aSelector is responsible for setting up an autorelease pool for the newly detached thread and freeing that pool before it exits.

My question is, do I need to create my own NSAutoreleasePool in my override of the -[NSOperation main] method, or is the creation of the NSAutoreleasePool handled by NSOperation?

5条回答
姐就是有狂的资本
2楼-- · 2020-02-24 12:40

yes, you need to.

- (void) main
{
  NSAutoreleasePool *thePool = [[NSAutoreleasePool alloc] init];
  //your code here
  //more code
  [thePool release];
}

if you don't create an autorelease pool, any convinience class-initializer (like [NSString stringWithFormat:]) will leak as these initializers return autoreleased objects.

查看更多
SAY GOODBYE
3楼-- · 2020-02-24 12:53

Yes, you do. You're defining a self-contained piece of work which the NSOperationQueue will execute on "some" thread, so you're responsible for managing memory in that work piece.

查看更多
Summer. ? 凉城
4楼-- · 2020-02-24 12:53

Yes, you need to create an NSAutoreleasePool in your [NSOperation main] method, unless you are creating a "concurrent" (slightly unfortunate nomenclature) NSOperation subclass and your overridden [NSOperation start] method creates the NSAutoreleasePool before calling `[NSOperation main].

The NSOperation class documentation has a good description of all of this: http://developer.apple.com/documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html.

查看更多
爷的心禁止访问
5楼-- · 2020-02-24 12:58

Good question, even Apple's own documents and example code aren't very clear on this. I believe I've found the answer though:

Because operations are Objective-C objects, you should always create an autorelease pool early in the implementation of your task code. An autorelease pool provides protection against the leaking of Objective-C objects that are autoreleased during your task’s execution. Although there might already be a pool in place by the time your custom code is executed, you should never rely on that behavior and should always provide your own.

Basically, even though there may be a pool in place as David mentioned, you should still create your own.

查看更多
走好不送
6楼-- · 2020-02-24 12:59

You don't need to create your own NSAutoreleasePool in your main, the system does it for you. To see this, use the Xcode menu command Run > Show> Breakpoints to open the Breakpoints window and type in: -[NSAutoreleasePool init]

Now run your program, and you'll see an autorelease pool getting created inside NSOperation.

See also, Apple's examples, for example, http://developer.apple.com/Cocoa/managingconcurrency.html which don't create their own autorelease pool.

查看更多
登录 后发表回答