Objective-C 属性
我只是想知道,当从类内访问属性时,我是否必须执行 [self someProperty]
或 self.someProperty
?或者将其简单地称为 someProperty
是否安全?
编辑:鉴于该属性的名称不冲突/影子......
I was just wondering, when accessing properties from within the class, do I have to do [self someProperty]
or self.someProperty
? Or is it safe to refer to it simply as someProperty
?
EDIT: Given that the name of the property doesn't conflict/shawdow....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
两者都可以。
.someProperty
表示法可以说更安全一些,因为如果您在那里输入错误,编译器会抛出错误;相比之下,输入错误的[self someProperty]
只会生成警告。Either will work. The
.someProperty
notation is arguably a little safer, as the compiler will throw an error if you make a typo there; by contrast, a mistyped[self someProperty]
will only generate a warning.在读取值时仅使用 someProperty 引用实例变量是可以的,但在设置值时,如果不使用 [self setSomeProperty:] 或 self.someProperty =,则不会发送键值观察消息。因此,如果任何其他对象正在观察此属性,它们将无法正确更新。
有时,这可以通过直接设置实例变量来实现,但通常您希望观察能够工作。
It's fine to refer to the instance variable using just someProperty when reading the value, but when setting the value, if you aren't using [self setSomeProperty:] or self.someProperty =, then there will by no key-value observing messages sent. So if any other object is observing this property, they won't be updated correctly.
This can, occasionally, be what you want by setting the instance variable directly, but usually you want observing to work.
任何一个都可以。但我不喜欢在类范围内使用 self 。
以上三个语句都是修改接口变量
someValue
。Any one is fine. But I prefer not to use
self
when being in scope of class.All the above three statements are going the modify the interface variable
someValue
.