NSAutoreleasePool:-
The NSAutoreleasePool class is used to support Cocoa’s reference-counted memory management system. An autorelease pool stores objects that are sent a release message when the pool itself is drained.
Why NSAutoreleasePool is needed?:-
To minimize the peak memory footprint. Use in block of code when you feel that there is lots of memory creation happened.
If your application creates a lot of temporary autoreleased objects within the event loop, however, it may be beneficial to create “local” autorelease pools to help to minimize the peak memory footprint.
USage:-
Important: If you use Automatic Reference Counting (ARC), you cannot use autorelease pools directly. Instead, you use @autoreleasepool blocks. For example, in place of:
Without ARC:-
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
|
// Code benefitting from a local autorelease pool.
|
[pool release];
With ARC :-
|
you would write:
@autoreleasepool {
|
// Code benefitting from a local autorelease pool.
|
}
|
@autoreleasepool blocks are more efficient than using an instance of NSAutoreleasePool directly; you can also use them even if you do not use ARC.
More About NSAutoreleasePool
In a reference counted environment, Cocoa expects there to be an autorelease pool always available. If a pool is not available, autoreleased objects do not get released and you leak memory.
The Application Kit creates an autorelease pool on the main thread at the beginning of every cycle of the event loop, and drains it at the end, thereby releasing any autoreleased objects generated while processing an event. If you use the Application Kit, you therefore typically don’t have to create your own pools. If your application creates a lot of temporary autoreleased objects within the event loop, however, it may be beneficial to create “local” autorelease pools to help to minimize the peak memory footprint.
Since you cannot retain an autorelease pool (or autorelease it—see retain andautorelease), draining a pool ultimately has the effect of deallocating it.
Threads and NSAutoreleasePool
Each thread (including the main thread) maintains its own stack of NSAutoreleasePool objects (see “Threads”). As new pools are created, they get added to the top of the stack. When pools are deallocated, they are removed from the stack. Autoreleased objects are placed into the top autorelease pool for the current thread. When a thread terminates, it automatically drains all of the autorelease pools associated with itself.
This comment has been removed by the author.
ReplyDeletevery helpful for my site. I always follow your tips....
ReplyDeletejava training in chennai
Enhance the beauty of your home with our aesthetically pleasing, space-saving home lifts.
ReplyDeleteHome lifts
Home elevtators UAE
Home lifts Melbourne
Home lifts Malaysia
Vacuum lifts India