Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way of using @autoreleasepools?

I would like to know if the following code is a good way to use the new @autoreleasepool, should I use it this way or let the main autoreleasepool take care of the objects?

  • (void) callingAutoReleasedObject, would probably be my viewDidAppear, or similar function.

Thanks!

- (UIBarButtonItem*)backButton {
    UIBarButtonItem* backButton = [[UIBarButtonItem alloc] initWithTitle:@"CustomBackTitle"
                                                                   style:UIBarButtonItemStyleBordered
                                                                  target:nil
                                                                  action:nil];
    return [backButton autorelease];
}

- (void) callingAutoReleasedObject {

    @autoreleasepool {
        [[self navigationItem] setBackBarButtonItem:[self backButton]];
    }
}
like image 950
Konrad77 Avatar asked Dec 22 '22 02:12

Konrad77


1 Answers

From Apple's reference:

There are, however, three occasions when you might use your own autorelease pools:

  • 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 create an autorelease pool inside the loop to dispose of those objects before the next iteration. Using an autorelease pool in the loop helps to reduce the maximum memory footprint of the application.

  • If you spawn a secondary thread. You must create your own autorelease pool as soon as the thread begins executing; otherwise, your application will leak objects. (See “Autorelease Pools and Threads” for details.)

Personally I created several @autoreleasepool blocks in order to avoid HEAVY memory leaks, during background synchronization using Core Data, since the framework (which I love) creates an HUGE number of autoreleased objects, that MUST be drained to preserve available memory ;)

like image 111
daveoncode Avatar answered Jan 05 '23 08:01

daveoncode