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
?
yes, you need to.
if you don't create an autorelease pool, any convinience class-initializer (like [NSString stringWithFormat:]) will leak as these initializers return autoreleased objects.
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.
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 theNSAutoreleasePool
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.Good question, even Apple's own documents and example code aren't very clear on this. I believe I've found the answer though:
Basically, even though there may be a pool in place as David mentioned, you should still create your own.
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.