开发者

NSArray (and other Cocoa types) @property values

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 r开发者_Python百科esults, so I'm reaching out to SO for what will surely be a very embarrassing question.


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


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;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜