Search code examples
iosobjective-cmemory-managementnsautoreleasepool

What is the difference between NSAutoreleasePool and @autoreleasepool block?


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.


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).