Josh Sherick
Josh Sherick

Reputation: 2161

Should I use self. when releasing

I have a whole bunch of @property (nonatomic, retain) stuff going on when I'm defining my variables and i want to know:

In my dealloc method, should i release them [myGreatVariable release]; or [self.myGreatVariable release];. They are currently done in the former way. And how much does this really matter? Is it just good to get in the habit of doing this from now on, or should I go back and change all of them in all of my classes because things aren't actually getting released.

Upvotes: 0

Views: 137

Answers (3)

EricS
EricS

Reputation: 9768

The one problem with using "self.variable = nil" in dealloc is that it can trigger additional actions if you have overridden "setVariable". For example, some classes will signal a delegate whenever a variable changes values but you probably don't want to do that once you are in dealloc. It's a bit safer to use "[variable release]".

Hopefully ARC will make all of this go away soon.

Upvotes: 1

Ben Zotto
Ben Zotto

Reputation: 71028

Don't use [self.myGreatVariable release]. As Daniel notes, it will work in this context, but it is the most "bastardized" version, and would do the wrong thing anywhere outside -dealloc by likely leaving around a garbage reference in a property.

You should choose one of, and standardize on, either:

  1. [myGreatVariable release];
  2. self.myGreatVariable = nil;

(The choice is largely a personal preference. I only use the first form in dealloc, because setters are sometimes nontrivial and have side-effects, and the goal of dealloc is to get efficiently and clearly get rid of all the resources, not to get tripped up with accidental state changes.)

Upvotes: 3

Hot Licks
Hot Licks

Reputation: 47729

If you're in dealloc it doesn't matter, though the former is an itty bit more efficient. But you have the 3rd option of doing self.myFairlyGoodVariable = nil;, which relies on the setter method to do the release (though two or three itty bits less efficiently).

I suspect you'll find different arguments for what you should do. Some folks argue you should use the instance variable (sans self.) for all read accesses. Others will argue that you should use the property access (ie, with self.) pretty much everywhere. I tend to fall into the latter camp, but I could accept arguments from the other side.

It's important to be reasonably consistent, though. And if you work with others it's good if you can have a team "standard" for this.

(One thing I like to do is to put the dealloc method at the top of the .m file, vs at the bottom where it usually ends up. This way you will be more likely to remember to update the dealloc method when you add/change a property and the associated @synthesize statement.)

Upvotes: 2

Related Questions