1

Assuming I have the following class.

@interface MyObj : NSObject{
   int age;   
}

-(void) setAge: (int) anAge;
-(int) returnAge;
@end

@implementation MyObj

-(void) setAge:(int) anAge{
  age = anAge;
}

-(int) returnAge{
  return age;
}

If I then want to assign a value to the age variable I could use the class method to do the following in main.

MyObj *newObj = [MyObj new];
[newObj setAge:18];

However from messing around i've noticed that I seem to be able to directly access the ivar using the . notation. I get no warning or error with this.

MyObj *newObj = [MyObj new];
newObj.age = 20;

The end result appears to be same for both but I feel like I shouldn't be using the . notation to directly access ivars like this.

Should I be using getters and setters for all ivars or is directly accessing them like this ok?

Thanks

Reck
  • 81
  • 6
  • 1
    It is exactly the same. – Shmidt Sep 01 '14 at 11:07
  • syntax to access ivar directly is `newObj->age` – Bryan Chen Sep 01 '14 at 11:09
  • Dot syntax does **not** access instance variables directly. It is just another means of writing the invocation of the accessor methods. To prove it to yourself, try making the name of the instance variable different from the name of the property as reflected in the names of the accessor methods. – Ken Thomases Sep 01 '14 at 12:27

1 Answers1

0

I personally avoid declaring instance variables and accessing them directly. Instead I only declare properties using the @property statement. Recent objective-c compilers than automatically introduce their belonging instance variables (auto synthesis). Also getters and setters are then automatically added unless you declare such properties as read only or write only.

Using properties I never access the instance variables directly, except when implementing:

  • init methods of their containing class
  • when overwriting the getters/setters to retrieve/store the new value
  • dealloc methods

In all other places I only refer to the property by using the self.propertyName notation. This implicitly will call the property's get and set method. This has the advantage that you can introduce get and set methods at a later moment without modifying your existing code.

There are some good style guides that can tell you more about good objective-c code style such as:

Lars Blumberg
  • 19,326
  • 11
  • 90
  • 127
  • Hi Lars, i've heard about properties but i'm not that far into my book yet to have learn't about them :) Even though there's better ways to go about things than what i've written above. Just so I understand correctly is it bad practice to access the ivars using the . notation like I have above or is it perfectly acceptable? – Reck Sep 01 '14 at 11:01
  • I see. So while reading keep in mind that you might want to replace your ivar declarations with property declarations in the future. – Lars Blumberg Sep 01 '14 at 11:03