开发者

Property access, style or substance?

There are three different syntax styles开发者_如何学运维 for accessing properties of an object:

myProp = value;
self.myProp = value;
[self setMyProp: value];

Are these purely style choices or is there difference in substance?


self.myProp = value;

and

[self setMyProp: value];

are style choices, as they are using accessors to set values. That is, self.myProp essentially is the same as calling [self setMyProp] or [self myProp]. It will implement whatever mechanism you define in the @property tag (retaining, releasing as needed, etc).

However,

myProp = value;

is substantially different as it is simply an assignment. No consideration for releasing myProp's original pointer, retaining the new value, etc.


The first is an direct assignment to the iVar myProp. The second and third are the same. You should prefer the second or third, because when you use @synthesize the setter does the memory management for you.


myProp = value;

This is a direct assignment to a C variable. It's not a property access at all.

self.myProp = value;

This is syntactic sugar for:

[self setMyProp: value];

What does that mean? It means that the former is translated by the compiler into the latter before emitting the code for it. That is the only meaning of dot notation. As long as the class declares method myProp and setMyProp: dot notation will work. myProp does not need to be a property in the formal sense (i.e. declared with @property). It also does not need to be synthesized. There does not need to be a single instance variable to back it. As long as the two methods exist at run time (or the getter if you never assign to the property), you can use dot notation. It's orthogonal to Objective-C properties.

So the answer is that, yes, for your second two examples, it is purely a matter of style. Personally, I hate dot notation. It's an unnecessary pollution of the syntax of the language (by which I mean we now have two ways of expressing the sending of messages, one of which looks identical to a completely different language feature). /rant


Your examples #2 and #3 compile identically, but #1 has an important difference -- it does not call the setter. This makes it useful (required) inside the setter or else you will create an infinite loop.

For example, this setter creates an infinite loop:

- (void)setMyProp:(int)value
{
self.myProp = value;
}

The same is possible in the getter.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜