什么时候在 Objective-C 中使用 self ?
现在我使用 Objective-C 已有 5 个多月了,我的第一个应用程序也在 App Store 上发布了,但我仍然对该语言的核心功能存有疑问。
我什么时候应该使用 self
访问 iVar,什么时候不应该?
释放插座时,您在 viewDidUnload 中编写 self.outlet = nil
,而不是在 dealloc
中编写 [outlet release]
。为什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当您编写
self.outlet = nil
时,将调用方法[self setOutlet:nil];
。当您编写outlet = nil;
时,您可以直接访问变量outlet
。如果您使用@synthesizeoutlet;,那么方法
setOutlet:
会自动生成,并且如果您将属性声明为@property(retain)NSObject,它会在分配新对象之前释放对象插座;
。When you write
self.outlet = nil
the method[self setOutlet:nil];
is called. When you writeoutlet = nil;
you access variableoutlet
directly.if you use
@synthesize outlet;
then methodsetOutlet:
is generated automatically and it releases object before assigning new one if you declared property as@property (retain) NSObject outlet;
.非常非常重要的博客,了解 Objective C 中的属性 getter-setter 方法
http://useyourloaf.com/blog/2011/2/8/understanding-your-objective-c-self.html
Very very important blog to understand about properties getter-setter method in objective c
http://useyourloaf.com/blog/2011/2/8/understanding-your-objective-c-self.html
当您引用 @property 时,您可以使用 self。
通常它会被@synthesize'd。
如果您引用“私有”变量,则不要使用 self。通常,我将属性用于 UI 元素(例如 UIButtons)或我希望从其他类轻松访问的元素。
您可以使用 @private、@protected 修饰符显式强制可见性。但是,您不能使用 Objective-C 中不存在的私有方法。
关于nil、release和dealloc的部分与“self”的使用无关。你释放你保留的东西,你清空自动保留的东西。
你应该阅读 Objective-C 指南,它写得很好,很有启发性。
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.
你用自我。当您访问所在类的属性时(因此是 self )。基本上,当您想要保留一个值时,您可以使用 self ,但仅当您在属性定义中保留时才使用 self 。
release 只是释放您保留的对象。你不应该释放你没有保留的东西,因为它会导致崩溃(僵尸对象)。
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).