NSArray(和其他 Cocoa 类型)@property 值
在调试同事编写的代码的过程中,我偶然发现了以下让我困惑的问题:
NSMutableArray *array = [NSMutableArray array];
NSUInteger arrayCount = array.count;
为什么这个有效?它也适用于 NSDictionary 和其他类型,但在文档和 Cocoa 标头中都找不到这些 @property 定义。
谷歌搜索“NSArray property”并没有产生很多有用的结果,所以我向 SO 求助,这肯定是一个非常尴尬的问题。
While in the process of debugging code written by a co-worker, I stumbled across the following that has me mystified:
NSMutableArray *array = [NSMutableArray array];
NSUInteger arrayCount = array.count;
Why does this work? It also works for NSDictionary
and other types, but nowhere in the documentation nor Cocoa headers can those @property
definitions be found.
Googling for "NSArray property" doesn't yield many useful results, so I'm reaching out to SO for what will surely be a very embarrassing question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它之所以有效,是因为点语法与属性无关。它只是语法糖(虽然我不喜欢它,所以也许它是“语法盐”)。
当您使用点语法作为表达式(或等号右侧的表达式)的右值时,它会简单地变成:
当
点位于等号左侧(作为左值)时,它会将其变成设置器。所以:
变成
所以是的,你可以做像
myObject.retain
这样的事情。但是你永远不应该这样做。您应该只使用点语法作为声明属性的访问器(即,通过@property
显式声明的内容)。 <插入关于如何根本不应该使用点语法的评论。>有关更多信息,请查看有关点语法的文档 (特别是“不正确使用”部分)。
It works because dot syntax has nothing to do with properties. It is simply syntactic sugar (though I don't like it, so perhaps it's "syntactic salt").
When you use dot syntax as the rvalue to an expression (or the expression to the right of the equal sign), it simple turns:
Into
When the dot is to the left of the equal sign (as an lvalue), it turns it into the setter. So:
Becomes
So yes, you can do things like
myObject.retain
. But you should never ever do that. You should only ever use dot syntax as accessors to declared properties (ie, things that have been explicitly declared via@property
). <insert remark about how you should never use dot syntax at all.>For more information, checkout out the documentation on dot syntax (specifically the "incorrect use" section).
点语法实际上只是访问不带参数并返回像 array.count 这样的值的方法的替代方法。以这种方式实际访问方法是不好的形式。
它也可以用于 [object setValue:(id)something] 之类的东西,并通过执行 object.setValue = Something; 来访问它。
the dot syntax is actually just an alternative for accessing methods that either take no parameter and return a value like array.count. It is bad form to actually access the methods in that way.
It can also be used for things like [object setValue:(id)something] and access it by doing object.setValue = something;