简体   繁体   中英

Dot Operator in Objective-C 2.0

Just picking up Objective-C 2.0 and wanted to know if there is any advantage in using the dot operator for accessing properties instead of the "old" way. Short example of what I mean.

"old" way:

 [myFraction setNumerator: 1];
 [myFraction setDenominator: 3];

"new" way:

 myFraction.numerator = 1;
 myFraction.denominator = 3;

Thanks!

Rodrigo

The only difference is ease of typing and readability. The opinion of which is more readable differs from person to person:)

I use the dot syntax when I'm descending an object and use the bracket to actually set a property.

Like so:

[self.view setFrame:CGRectMake(0, 0, 320, 480)];

Instead of:

[[self view] setFrame:CGRectMake(0, 0, 320, 480)];

I actually like the new syntax - but maybe because I work as Python programmer.

The dot-property syntax meshes nicely with key-paths in KVC/KVO. It looks neater to my eyes than nested brackets (and I like scheme, so I'm not opposed to parentheses nesting,), and makes it explicit when you are accessing a property. rather than passing a message - even though the mechanism is the same.

And, I see property access of an object being (basically) the same operation as accessing members of a struct or union, so the syntax should be the same.

I'll argue for the old way:

The square-bracket syntax maxes it obvious that you are accessing the members of an Objective-C object, while the dot syntax indicates that you are dealing with a C struct (or union).

Beyond than that, it is simply a matter of personal choice and more/less typing.

C++ and C# programmers probably will more naturally adapt to the dot operator when accessing member variables since it has similar usage in those languages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM