Advanced Memory Management Programming Guide says regarding @autoreleasepool:
Use Local Autorelease Pool Blocks to Reduce Peak Memory Footprint
Many programs create temporary objects that are autoreleased. These objects add to the program’s memory footprint until the end of the block. In many situations, allowing temporary objects to accumulate until the end of the current event-loop iteration does not result in excessive overhead; in some situations, however, you may create a large number of temporary objects that add substantially to memory footprint and that you want to dispose of more quickly. In these latter cases, you can create your own autorelease pool block. At the end of the block, the temporary objects are released, which typically results in their deallocation thereby reducing the program’s memory footprint.
The following example shows how you might use a local autorelease pool block in a for loop.
NSArray *urls = <# An array of file URLs #>;
for (NSURL *url in urls) {
@autoreleasepool {
NSError *error;
NSString *fileContents = [NSString stringWithContentsOfURL:url
encoding:NSUTF8StringEncoding error:&error];
/* Process the string, creating and autoreleasing more objects. */
}
}
Can this code also be written without autoreleasepool and efficiently managed?
like creating a property of fileContents
and setting it nil
after processing it.
self.filecontents = nil;
fileContents = nil
by[fileContents release]
in my suggested answer below). – Martin Rautorelease
block format was introduced with ARC. Autoreleased objects within a loop will not be released until the run loop hits the next iteration (becauseUIKit
runs each event in aautoreleasepool
block), unless using anautoreleasepool
. – danielbeard