Conceptual question about NSAutoreleasePools
In my Cocoa program, wouldn't a really simple way of dealing with autoreleased objects be to just create a tim开发者_StackOverflower 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?
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?
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.
精彩评论