thiagocfb
thiagocfb

Reputation: 487

Is it OK to use dot syntax to call methods?

I'm trying to learn how to develop using objective C and I read on this book that to access an ivar from a class using dot syntax (obj.var) you must implement these vars using @properties, however I've tried using this kind of access without defining @properties for these vars and it seemed to work normally.

How does this kind of access works ? Is it a good practice to use it like it's in Java ?

Example:

ComplexNumber *c1 = [[ComplexNumber alloc]init];
c1.realPart = 3;
c1.imaginaryPart = 2;

ComplexNumber's methods:

- (double)modulus;
-(void)setRadius:(double)aRadius phase:(double)aPhase;
-(void)print;
-(double)realPart;
-(double)imaginaryPart;
-(void)setRealPart:(double)value;
-(void)setImaginaryPart:(double)value;

Upvotes: 2

Views: 146

Answers (2)

deleted_user
deleted_user

Reputation: 3805

No its not a good practice, you technically can access zero argument methods using dot syntax but now Xcode will warn you about doing this. This is against Apple's coding guidelines.

Bracket syntax should be used for calling methods.

Upvotes: 4

Caleb
Caleb

Reputation: 125017

A property is just a promise that the class implements certain methods. The dot syntax is simply translated into calls to methods with the appropriate name, depending on what the code is doing:

b = a.foo;          // becomes 'b = [a foo];'
a.foo = b;          // becomes '[a setFoo:b];'

So you can actually get away with using dot syntax to call methods even when those methods aren't properties. That can be sort-of okay if the method represents something that works like a property, such as accessing the length method of an array:

len = myArray.length // becomes 'len = [myArray length];'

But mostly you shouldn't do it. It takes something that's not a property and makes it look like a property. It might work, but it's going to confuse people who look at the code (including the future you). You definitely shouldn't use it to call methods that have side effects because property accessors aren't expected to have side effects.

Upvotes: 6

Related Questions