Konrad77
Konrad77

Reputation: 2535

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?

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]];
    }
}

Upvotes: 4

Views: 1330

Answers (4)

daveoncode
daveoncode

Reputation: 19618

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 ;)

Upvotes: 8

Abizern
Abizern

Reputation: 150745

Another reason to create an autoreleasepool is if you are in a loop that creates lots of autoreleased objects.

Upvotes: 2

justin
justin

Reputation: 104708

You would generally create an autorelease pool when:

  • your program starts
  • you start a new thread
  • you receive a callback from a C or C++ interface, and you don't know when the caller's set a pool up for you
  • when you create a lot of autoreleased objects Really, this should be more common than many people use them. They're quite lightweight to create.
  • when autoreleased objects' data/ivars which are large and may be freed early with a pool in place. for example, an objc object which holds pixel data or audio data.
  • when debugging ref count offsets.

For something as simple as your example, don't bother.

Upvotes: 1

npellow
npellow

Reputation: 1985

The only reason you should need to define your own autorelease pool is if you also creating your own threads.

For what you are doing above, definitely just use the main autorelease pool.

Upvotes: 0

Related Questions