Volomike
Volomike

Reputation: 24916

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.

Upvotes: 2

Views: 2537

Answers (2)

newacct
newacct

Reputation: 122518

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.

Upvotes: 1

nielsbot
nielsbot

Reputation: 16031

If you are using AppKit, you don't have to create autorelease pools:

The Application Kit creates an autorelease pool on the main thread at the beginning of every cycle of the event loop, and drains it at the end, thereby releasing any autoreleased objects generated while processing an event. If you use the Application Kit, you therefore typically don’t have to create your own pools. If your application creates a lot of temporary autoreleased objects within the event loop, however, it may be beneficial to create “local” autorelease pools to help to minimize the peak memory footprint.

(link)

Upvotes: -1

Related Questions