Reputation: 2535
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
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
Reputation: 150745
Another reason to create an autoreleasepool is if you are in a loop that creates lots of autoreleased objects.
Upvotes: 2
Reputation: 104708
You would generally create an autorelease pool when:
For something as simple as your example, don't bother.
Upvotes: 1
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