When to use `self` in Objective-C?

风流意气都作罢 提交于 2019-12-22 07:57:16

问题


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?


回答1:


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




回答2:


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




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/7254707/when-to-use-self-in-objective-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!