简体   繁体   中英

Accessing ivars using the . notation

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

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:

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