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. 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:
A property declaration is equivalent to one (
readonly) or two (readwrite/default) instance-method declarations. Keywords likeretaintell 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, orcopy), 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.lengthormyArray.countormyView.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
@propertywill 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.