开发者

Should I use self. when releasing

开发者 https://www.devze.com 2023-04-10 01:33 出处:网络
I have a whole bunch of @property (nonatomic, retain) stuff going on when I\'m defining my variables and i want to know:

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 thin开发者_开发知识库gs aren't actually getting released.


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.)


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.)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号