Apple says that this is a good idea for saving memory. What would that look like in code?
Asked
Active
Viewed 2,547 times
1 Answers
11
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.

iPera
- 1,053
- 1
- 12
- 24
-
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 Apr 12 '09 at 22:07
-
1Keep in mind that Apple recommends using [pool drain] instead of [pool release] as a habit for future compatibility with GC environments. – Marc Charbonneau Apr 13 '09 at 01:15
-
@Marc Charbonneau then wouldn't you get a leak for not calling release on the pool? – Dan Rosenstark Jan 10 '11 at 21:46
-
Nope, in a reference counted environment calling drain is the same as calling release. Check the docs for more information on the differences between GC and non-GC environments. – Marc Charbonneau Jan 24 '11 at 03:12