Let’s say I’m developing a game. I run the following class method thousands of times:
NSBundle *bundle=[NSBundle mainBundle];
I do not create an autorelease pool and release the objects that call the above class method all the time. I create an object, it calls the above class method, I release it, and on, and on, thousands of times.
3 questions:
- Is memory leaked?
- If I ran:
NSAutoReleasePool *pool=[[NSAutoReleasePool alloc] init];
[pool drain];
would it then effectively release all those NSBundles created in the class method?
- if I wrote:
pool=nil;
instead of writing:
[pool drain];
Would the same effect be achieved? Is this good practice?
The three questions are correlated and I will boost the one that clarifies them 🙂
[NSBundle mainBundle]returns an autoreleased object, so the autorelease pool will take care of it. However, if you’re going to call it a bunch of times in one function or something, you’d be better off either getting a reference to it once and just holding on to it while you need it, or creating your own autorelease pool.NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];that is autoreleased will go intopool, and after you drain the pool, they’ll be released. Note:[pool drain];also releases the pool, so don’t call[pool drain]; [pool release];or you will send thereleasemessage to the object twice and probably crash.pool = nil;would just lose the reference topooland the actualpoolobject would be leaked. You have to call either[pool drain];or[pool release];and good practice would be to setpool = nil;afterwards.