fundtimer
fundtimer

Reputation: 809

A more definitive answer on when to release an object

I know this has been answered before (sort of) but I've been reading conflicting answers on exactly when or when not to release an object that has not been specifically subclassed via an allocation.

For example, if I do the following:

@property (..., retain) NSMutableArray *myArray;

or in general,

@property (some retain attribute - strong, weak, retain) type myObject;

After synthesization, If I do nothing else to myObject (no allocation or even forget to use it), are there any cases in which I'm still responsible to release it?

Upvotes: 0

Views: 71

Answers (1)

Matt Wilding
Matt Wilding

Reputation: 20153

There are two totally different answers depending on whether or not you're using ARC. Since the ARC environment is pretty straight forward, I'll just answer from a pre-ARC perspective. The main thing to understand is that all of the talk around property retain semantics is just a distraction from the main point: If you take ownership, you must relinquish it. Relinquishing ownership is done via -release. So, what you need to understand is "What counts as taking ownership?"

By convention, any time you send a message to class that contains any of [new, alloc, retain, copy], you now own that object. The compiler generates setter methods for Objective C Properties depending on the ownership policies you specify. For example...

@property (..., retain) NSMutableArray *myArray;
@synthesize myArray = _myArray;

This generates a method that looks like this1:

- (void)setMyArray:(NSMutableArray *)myArray
{
    // This is oversimplified, just to illustrate the important point.
    // Again, this is NOT the way a setter would actually be synthesized.
    [_myArray release];
    _myArray = [myArray retain];
}

So now, when you say something like self.myArray = someArray, you know you've sent a retain message to someArray, and you're responsible for releasing it later. The ideal way to do that is to say self.myArray = nil, because it releases the old value before retaining nil. Note that it's also perfectly safe to send that message, even if you never set anything to the myArray property, because sending messages to nil is okay. That's why it's common to always set owned properties to nil when you're done with them, regardless of how they're being used.


1 For a study on how accessors should actually work, see this article.

Upvotes: 3

Related Questions