Retain/release of returned objects

Jörgen Sigvardsson picture Jörgen Sigvardsson · Aug 16, 2011 · Viewed 9.3k times · Source

I am new to Objective-C, so this might be a dumb question.

I cannot help but see the similarities between ObjC and Microsoft's COM with respect to memory management (AddRef/Release vs retain/release). In a COM environment, it's more or less imposed on you to always AddRef (retain) an object before returning it to the caller. From what I've seen so far (I'm a third through Cocoa® Programming for Mac® OS X (3rd Edition)), the memory management part is somewhat fuzzy.

Assuming there is no GC, what is the idiomatic way to return an object?

Answer

hamstergene picture hamstergene · Aug 16, 2011

Read Memory Management Programming Guide about autorelease pools.

In Objective-C, by convention, objects should be returned autoreleased (unless the method returning the object has a name that begins with “alloc”, “new”, “copy”, or “mutableCopy”). Autoreleased objects are tracked by Objective-C in a pool and automatically handled, which means you don't need to care about sending a final release to them. This greatly simplifies reference counting compared to COM, and this is why you're not seeing any release calls on returned objects most of the time. In contrast, the same convention specifies that all objects returned by a method whose name begins with alloc, new, copy, or mutableCopy, are the responsibility of the method caller. You have to manually call release on these objects or your program will have memory leaks.