NSArray(和其他 Cocoa 类型)@property 值

发布于 2024-10-19 03:04:46 字数 295 浏览 2 评论 0原文

在调试同事编写的代码的过程中,我偶然发现了以下让我困惑的问题:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

千紇 2024-10-26 03:04:46

它之所以有效,是因为点语法与属性无关。它只是语法糖(虽然我不喜欢它,所以也许它是“语法盐”)。

当您使用点语法作为表达式(或等号右侧的表达式)的右值时,它会简单地变成:

bar = myObject.thing;

bar = [myObject thing];

点位于等号左侧(作为左值)时,它会将其变成设置器。所以:

myObject.thing = 42;

变成

[myObject setThing:42];

所以是的,你可以做像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:

bar = myObject.thing;

Into

bar = [myObject thing];

When the dot is to the left of the equal sign (as an lvalue), it turns it into the setter. So:

myObject.thing = 42;

Becomes

[myObject setThing:42];

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

沫雨熙 2024-10-26 03:04:46

点语法实际上只是访问不带参数并返回像 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;

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文