Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is autoreleasepool? [duplicate]

Possible Duplicate:
Why use Autorelease pool?

All Objective-C starting page opens with a default @autoreleasepool{...} statement under the main function declaration. But what is this statement actually doing? The new Objective-C releases automatically objects and deleting the line changes nothing to the program. Is this command really necessary?

like image 410
moray95 Avatar asked Feb 03 '13 20:02

moray95


People also ask

What is @autoreleasepool?

An autorelease pool stores objects that are sent a release message when the pool itself is drained. Important. If you use Automatic Reference Counting (ARC), you cannot use autorelease pools directly. Instead, you use @autoreleasepool blocks.

What is Autoreleasepool in Swift?

The autoreleasepool allows you to explicitly manage when autorelease objects are deallocated in Swift, just like you were able to in Objective-C. Note: When dealing with Swift native objects, you generally will not receive autorelease objects.


1 Answers

The @autoreleasepool statement is doing the same job as before, instead of using the NSAutoreleasePool class. The way the NSAutoreleasePool worked was a bit weird, as creating it caused an effect throughout the whole application; @autoreleasepool creates a scoped area and makes it clearer what's within the pool and when it drains (when it goes out of scope). It's also more efficient according to Apple.

The concept of an autorelease pool is simple, whenever an object instance is marked as autoreleased (for example NSString* str = [[[NSString alloc] initWithString:@"hello"] autorelease];), it will have a retain count of +1 at that moment in time, but at the end of the run loop, the pool is drained, and any object marked autorelease then has its retain count decremented. It's a way of keeping an object around while you prepare whatever will retain it for itself.

With ARC, whilst the autorelease method isn't used by the developer, the underlying system that manages ARC inserts that for you. (Remember: All ARC is doing is inserting retain, release and autorelease calls for you at the appropriate times). Because of this, the existing AutoreleasePool concept needs to stay around.

If you remove the autorelease pool, your objects will start leaking

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. In this situation, your program will typically log suitable warning messages.

like image 100
WDUK Avatar answered Sep 21 '22 13:09

WDUK