views:

335

answers:

2

Apple says that this is a good idea for saving memory. What would that look like in code?

+3  A: 

Usualy you don't need to create autorelease pool, because system cares about this. But, sometimes you need to do this. It's usualy in big loops. Code would look like this:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int i;    
for (i = 0; i < 1000000; i++) {    
  id object = [someArray objectAtIndex:i];
  // do something with object
  if (i % 1000 == 0) {
    [pool release];
    pool = [[NSAutoreleasePool alloc] init];
  }
}
[pool release];

Autorelease pools are kept as a stack: if you make a new autorelease pool, it gets added to the top of the stack, and every autorelease message puts the receiver into the topmost pool.

mperovic
Good description. Calling objectAtIndex: however does not add anything to the autorelease pool, so it's OK to use it in a loop without the autorelease pool.
Chris Lundie
Keep in mind that Apple recommends using [pool drain] instead of [pool release] as a habit for future compatibility with GC environments.
Marc Charbonneau