NSArray (and other Cocoa types) @property values

匿名 (未验证) 提交于 2019-12-03 01:01:02

问题:

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.

回答1:

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



回答2:

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;



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!