Confusion About Objective-C's Memory Management (Cocoa)

Hello everyone,

There is one thing about Objective-C's memory management that confuses me, which is a returned object's lifetime from methods with names doesn't start with "alloc", "new", "copy", or "mutableCopy".

Take this as an example, when using NSBitmapImageRep's representationUsingType:properties: method, it returns an NSData object (reference: https://developer.apple.com/documentation/appkit/nsbitmapimagerep/representation(using:properties:)?language=objc).

While testing this out, the NSData seemed to be an owned object (it doesn't get released until the end of the program).

From what I understand, this may be an auto-released object which is released at the end of an autorelease pool block.

Could someone explain this in more detail? What if I want to release that NSData object before the end of the autorelease pool block? How can I know which object is autoreleased, borrowed, or owned?

Answered by DTS Engineer in 823351022

+1 to both of the above replies, but also…

I recommend that you check out Objective-C Memory Management for Swift Programmers, which covers this stuff in some detail.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

The only way to force a release of an autoreleased object is to create your own autorelease pool with a smaller scope.

In theory, you can use the method names to determine ownership and responsibilities. The documentation usually tells you too.

With modern ARC code, it usually isn't too big of a problem.

What if I want to release that NSData object before the end of the autorelease pool block?

You can set the object to nil explicitly before the pool is drained if you are concerned it may stay in memory, or has other references that may keep it alive.

+1 to both of the above replies, but also…

I recommend that you check out Objective-C Memory Management for Swift Programmers, which covers this stuff in some detail.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Confusion About Objective-C's Memory Management (Cocoa)
 
 
Q