self.var 和简单 var 之间的区别
在 Objective-C 类中使用 self.var
与仅使用 var
有什么区别?对其中一方有利还是有危险?
What is the difference between using self.var
vs. just var
in an Objective-C class? Are there benefits or dangers to one or the other?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
self.var
调用var
的属性。在幕后,Objective-C 会自动生成属性的 getter(如果愿意的话,您也可以自己制作一个 getter),因此 self.var 使用该 getter。 Plainvar
直接访问实例变量(即,它不通过 getter 来获取值)。self.var
calls the property forvar
. Behind the scenes, Objective-C automatically generates a getter for properties (or you can make one yourself, if so inclined), soself.var
uses that getter. Plainvar
accesses the instance variable directly (i.e., it doesn't go through the getter to get the value).相同
在概念上与使用点符号
,您实际上是在向自己发送消息。在概念上与 相同
因此,不使用点表示法访问实例变量与将 self 视为指向 C 结构体的指针并直接访问结构体字段相同。
在几乎所有情况下,最好使用该属性(点符号或消息发送符号)。这是因为可以使该属性自动执行必要的保留/复制/释放以阻止内存泄漏。另外,您可以使用 使用属性观察键值。子类还可以重写属性以提供自己的实现。
使用属性的两个例外是在 init 中设置 ivar 和在 dealloc 中释放它时。这是因为您几乎肯定希望避免在这些方法中意外使用子类重写,并且您不想触发任何 KVO 通知。
is conceptually identical to
So using dot notation, you are really sending messages to self.
is conceptually the same as
So not using dot notation to access an instance variable is the same as treating self as a pointer to a C struct and accessing the struct fields directly.
In almost all cases, it is preferable to use the property (either dot notation or message sending notation). This is because the property can be made to automatically do the necessary retain/copy/release to stop memory leaks. Also, you can use key value observing with a property. Also subclasses can override properties to provide their own implementation.
The two exceptions to using properties are when setting an ivar in init and when releasing it in dealloc. This is because you almost certainly want to avoid accidentally using a sub class override in those methods and you don't want to trigger any KVO notifications.
重复
以及您可以通过使用“搜索”框在大约 15 秒内找到的大约十几个其他内容网站的右上角。
Duplicate of
and probably about a dozen others that you could've found in about 15 seconds by using the "Search" box up in the top right corner of the site.