// *** before: ***
// the pool was an ordinary object, and it had to be drained by hand -
// including on every early exit from the loop
int main(int argc, char *argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int result = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return result;
}
- (void)processFiles:(NSArray *)paths {
for (NSString *path in paths) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *text = [NSString stringWithContentsOfFile:path];
[self handle:text];
[pool drain]; // a break above this line leaked the pool
}
}
// *** in version 2011: ***
// @autoreleasepool is a language construct: the pool is drained on any way
// out of the braces - return, break, or an exception
int main(int argc, char *argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, nil);
}
}
- (void)processFiles:(NSArray *)paths {
for (NSString *path in paths) {
@autoreleasepool { // memory is released every step
NSString *text = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:nil];
[self handle:text];
if (text.length == 0) break; // the pool is drained anyway
}
}
}
// it is faster than NSAutoreleasePool as well: the runtime keeps the pool
// on a stack instead of allocating an object