When to use `self` in Objective-C?
It's now more than 5 months that I'm in Objective-C, I've also got my first app published in the App Store, but I still have a doubt about a core functionality of the language.
When am I supposed to use self
accessing iVars and when I'm not?
开发者_JAVA技巧When releasing an outlet you write self.outlet = nil
in viewDidUnload, instead in dealloc
you write [outlet release]
. Why?
When you write self.outlet = nil
the method [self setOutlet:nil];
is called. When you write outlet = nil;
you access variable outlet
directly.
if you use @synthesize outlet;
then method setOutlet:
is generated automatically and it releases object before assigning new one if you declared property as @property (retain) NSObject outlet;
.
Very very important blog to understand about properties getter-setter method in objective c
Understanding your (Objective-C) self
http://useyourloaf.com/blog/2011/2/8/understanding-your-objective-c-self.html
You use self when you are refering to a @property. Usually it will have been @synthesize'd.
You do not use self if you are refering to a "private" variable. Typically, I use properties for UI elements such as UIButtons or for elements I want easily reachable from other classes. You can use the @private, @protected modifiers to explicitly enforce visibility. You cannot however use private methods, that do not exist in Objective-C.
The part about nil, release and dealloc is unrelated to the use of "self". You release what you retained, you nil what is autoretained.
You should read the Objective-C guide, it's well written and very enlightening.
You use self. when you're accessing properties of class that you're in (hence self). Basically you use self when you want to retain a value, but is only when you have retain in your property definition.
release just releases object that you've retained. You shouldn't release something that you haven't retained cuz it will lead to crash (zombie object).
精彩评论