views:

50

answers:

2

In my Cocoa program, wouldn't a really simple way of dealing with autoreleased objects be to just create a timer object inside the app delegate that calls the following method e.g. every 10 seconds:

if (pool) {
    // Release & drain the current pool to free the memory.
    [pool release];
}

// Create a new pool.
pool = [[NSAutoreleasePool alloc] init];

The only problems I can imagine are:

1) If the above code runs in a separate thread, an object might get autoreleased between the release call to the old pool and the creation of the new pool - that seems highly unlikely though.

2) It's obviously not that efficient, because the pool might get released if there's nothing in it. Likewise, in the 10 second gap, many many objects might be autoreleased, causing the pool to grow a lot.

Still, the above solution seems pretty suitable to small and simple projects. Why doesn't anybody use it? What's the best practice of using NSAutoreleasePools?

+3  A: 

You don't need to use an autorelease pool at all, unless you're explicitly creating threads on your own. The framework should handle all this stuff for you pretty well; maybe you're misunderstanding what happens to an object when you send it an autorelease message?

Carl Norum
I thought you had to `release` an NSAutoreleasePool to free up the memory used by the autoreleased objects. Am I wrong?
@ryyst, yes you are wrong. The autorelease pool gets cleared out at the end of each event loop. The only time you need to do it on your own is in some special threading circumstances.
Carl Norum
OK, thanks! So in the end, it actually works kind of like I posted above (regularly freeing the memory).
@ryyst: Yes, it does, but just for trivia, instead of using a timer, you would probably want to use a runloop observer and clear it at a specific point through each iteration of the loop. Again, though, you would only do this if you are creating and managing your own threads.
Jason Coco
ryyst: You need to release an autorelease pool when you create an autorelease pool; specifically, you need to release the pool you create. You usually don't need to create a pool in a normal Cocoa application.
Peter Hosey
A: 

An NSAutoreleasePool is always thread local.

The pool will be automatically flushed every tick of the run loop. Between the 10 seconds when your NSTimer fires, there are already over hundreds of ticks passed, so the pool has been cleared over hundreds times.

KennyTM