Search code examples
c++objective-cmemory-managementxcode7nsautoreleasepool

Proper Usage of @autoreleasepool


I'm mixing some ObjectiveC and C++ in my code. (My files are .mm files instead of .m.) When is the proper reason to wrap any code block with @autoreleasepool? Not knowing what I'm doing, I'm wrapping any block of code that may contain any non-ObjectiveC variable, whether it be int, char, std::string, or any pointer thereof of a non-ObjectiveC variable. So, every class method in my C++ class has an @autoreleasepool wrapper inside it.

Am I doing it wrong?

Note that on previous questions sort of related to this question, they talk about using alloc, init, and release, and these seem to be deprecated now in XCode7+. So, I need the latest advice on this, not old advice. I need advice pertaining to XCode7 or greater.


Solution

  • Autorelease pools are for limiting the lifetimes of things that were autoreleased inside it. autorelease is a Cocoa Objective-C API, so only Objective-C code can autorelease things. So it would never make any sense to put an autorelease pool around a block of pure C/C++ code that you are sure never calls into Objective-C code.

    Autorelease pools are usually only useful for situations where you have a loop that runs many times where each iteration may perform lots of autorelease. Note that not all Objective-C code will autorelease; it's not obvious. Some Cocoa APIs will autorelease and some will not. If it's all your own code written in ARC, it will probably not autorelease.