What is autoreleasepool? [duplicate]
Asked Answered
F

1

73

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?

Files answered 3/2, 2013 at 20:39 Comment(2)
Or maybe #8715375Clothier
info to the title: <Advanced Memory Management Programming Guide> developer.apple.com/library/archive/documentation/Cocoa/…Virginavirginal
M
97

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.

Maguire answered 3/2, 2013 at 20:58 Comment(2)
Does this mean that if I use ARC and release an object from somewhere outside the @autoreleasepool{} the object still exists until the end of the @autoreleasepool block?Occident
If you manually release an autoreleased object, when you hit the end of the autorelease pool the dealloc'd object will no longer exist and you will hit an exception likely somewhere in frameworks or machine code. If it's a long pathway of code, your app can seem to crash in a seemingly unrelated spot causing confusion.Accusation

© 2022 - 2024 — McMap. All rights reserved.