开发者

How does dot syntax work without explicit @property in Objective-C?

I wrote a setter and getter method following Apple's conventions and noticed that despite having no variable I can still access the setter and getter using the dot syntax. 开发者_Python百科Is this normal behavior? What enables this feature?

Example:

// Header definition. Keep in mind there is no class variable or @property for height.
- (void)setHeight:(float)height;
- (float)height;

// else using the dot syntax.
object.height = 10.0f;


A property-access expression is equivalent to a message expression:

[object setTexture:tex];

A property declaration is equivalent to one (readonly) or two (readwrite/default) instance-method declarations. Keywords like retain tell the compiler how to implement the method if you tell it to do so (@synthesize).

However, you can skip the property declaration and declare the methods directly, as shown in your question. You can't synthesize their implementations, since you need a property declaration for that (otherwise, it wouldn't know what memory-management policy to use: assign, retain, or copy), but you can always implement the methods yourself.

Then, even though you declared and implemented the methods yourself, since property-access syntax and message syntax are equivalent to each other, you can use the methods whichever way you want: With a message expression, or with a property-access expression.

Some would consider it bad form, though, to use property access expressions on anything but a formal @property (e.g., myString.length or myArray.count or myView.frame). It definitely is bad form to use a property-access expression to send a message that doesn't access any kind of property; foo.retain.autorelease, for example, is bad and wrong: It reeks of trying to pretend you're programming some other language than Objective-C.

Incidentally, a property and a variable are unrelated. A @property will ordinarily be backed by an instance variable, but this is not required: You could store the property's value inside another object, or convert it to and from some other format, or both. Likewise, accessing a property (which is an accessor message) and accessing an instance variable (which is just accessing a variable, nothing more) are very different.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜