Monday 31 August 2015

Autorelease Pool Blocks

Autorelease pool is an object (instance of NSAutorelease class) which will be created at the starting of thread run loop and released at the end of run loop.

When you call autorelease on any object that object will be added to autorelease pool and finally when pool is getting released all the objects in the pool will be released. The main purpose of autorelease is to release the object some time later(at end of run loop) but not immediately.

Three occasions when you might use your own autorelease pool blocks.
  • If you are writing a program that is not based on a UI framework, such as a command-line tool. 
  • If you write a loop that creates many temporary objects. You may use an autorelease pool block inside the loop to dispose of those objects before the next iteration. Using an autorelease pool block in the loop helps to reduce the maximum memory footprint of the application. 
  • If you spawn a secondary thread.
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. */
    }
}
Documentation

No comments:

Post a Comment