Question

I want to know what are the differences between NSAutoreleasePool and @autoreleasepool block.I have gone through a number of questions but didn't get any satisfying answer.Till now I came to know that in ARC we can't use NSAutoreleasePool and @autoreleasepool block can be used in both ARC enabled and disabled case.So in what respect they are different internally to behave in that way.

Is it necessary to release the objects in an arc disabled environment even though we are using NSAutoreleasePool or @autoreleasepool block or they will do it automatically?Also,if ARC release memory automatically then why we use @autoreleasepool block.Please give me a brief overview with example.

Was it helpful?

Solution

One difference you mentioned :

In ARC we can't use NSAutoreleasePool and @autoreleasepool block can be used in both ARC enabled and disabled case.

But for yours this statement :

Also,if ARC release memory automatically then why we use @autoreleasepool block

ARC doesn't release memory automatically! It's a compile time feature where every object is sent an autorelease and it goes to the local pool. Once its lifetime and scope are over, the pool OS releases itself resulting in the release of all objects.

You may refer this blog Are @autoreleasepool Blocks More Efficient?

Is it necessary to release the objects in an arc disabled environment even though we are using NSAutoreleasePool or @autoreleasepool block or they will do it automatically?

Yes you need to release the objects. As per definition of (@/NS)autoreleasepool, it doesn't handle your object retain counts but it is used only for the following :

Autorelease pool blocks provide a mechanism whereby you can relinquish ownership of an object, but avoid the possibility of it being deallocated immediately (such as when you return an object from a method).

OTHER TIPS

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.

Also, If you use Automatic Reference Counting (ARC), you cannot use autorelease pools directly. Instead, you use @autoreleasepool blocks. For example, in place of:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Code benefitting from a local autorelease pool.
[pool release];

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.

You can refer the Apple document for more detail:

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSAutoreleasePool_Class/Reference/Reference.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top