views:

2007

answers:

5

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  A: 

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.

Graham Lee
+1  A: 

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.

Barry Wark
+5  A: 

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.

DavidPhillipOster
A: 

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.

Jaroslaw Szpilewski
+3  A: 

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.

Marc Charbonneau