开发者

How often should I put NSAutoreleasePools in place?

开发者 https://www.devze.com 2023-01-23 21:19 出处:网络
Hey, I am making a cocoa touch static library, And I have this problem: I am running my project in the simulator with the Leaks instrument, And I am coming up开发者_StackOverflow中文版 with leaks for

Hey, I am making a cocoa touch static library, And I have this problem:

I am running my project in the simulator with the Leaks instrument, And I am coming up开发者_StackOverflow中文版 with leaks for autoreleased objects.

I know for a fact that I have at least one NSAutoreleasePool in place at a time (in my main() method), my question is, how often should I put in others (I am developing for iPhone and iPad if that matters)

UPDATE: I have figured out that, for some reason, my code isn't exiting out of the UIApplicationMain() call on iOS 4, I am just getting a SIGKILL signal, and my autorelease pool isn't draining. How can I fix that (I mean the app getting a SIGKILL)

Thanks


NSAutoreleasePool is required when you run something in a background thread, so if your functions can be run in a background then you need to create a autorelease pool in them:

- (void) willRunInBackground{
   NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
   ...
   [pool drain];
}

The second situation where NSAutoreleasePool will be useful is when you create many autoreleased objects in a loop - to avoid to much autoreleased objects hanging around you can create and drain autorelease pool on loop iteration (as Joe mentioned).

But you memory leaks are likely caused by the 1st reason - each thread must have its own NSAutoreleasePool to handle autoreleased objects.


The fact that you are autoreleasing objects does not, in itself, prevent a memory leak. Since you're not seeing messages in Console telling your that your objects are being autoreleased outside a pool, it indicates that the problem isn't that they're not being put into a pool.

You must not be managing your retain count properly. Remember that all calls to -alloc and -copy must be balanced by calls to -release or -autorelease. Perhaps you aren't releasing your member variables in a class's dealloc method somewhere. Start by using Instruments to find where you are allocating / copying your objects, then look at every place you retain and release them to ensure each object's retain count is balanced.


From the WWDC videos standard practice holds that a tight loop with a lot of variables flying around is a good place to put one. Start it before the loop, everything in the loop that is autoreleased should go to that pool, and drain it afterward.

0

精彩评论

暂无评论...
验证码 换一张
取 消