Reputation: 1047
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?
When releasing an outlet you write self.outlet = nil
in viewDidUnload, instead in dealloc
you write [outlet release]
. Why?
Upvotes: 4
Views: 2239
Reputation: 17877
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;
.
Upvotes: 6
Reputation: 5389
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.
Upvotes: 1
Reputation: 13180
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
Upvotes: 3
Reputation: 1079
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).
Upvotes: 0