Search code examples
iosobjective-cpropertiesselfsynthesize

Which is best:calling a property by @synthesize or by using self keyword


Posting an ObjectiveC beginner level question. When I used properties to declare objects I see that we can access a particular property by 2 methods.

@property(nonatomic,retain) NSString *str;
  1. Use @synthesize propertyname eg: @synthesize str;

  2. By using keyword self eg: self.str;

So what is the difference between these 2 methods and which is more suitable. Thanks for your time


Solution

  • @synthesize can not be used to access the property. It is a compiler directive. When you declare a property using using @property, the accessor methods (getter and setter) are automatically generated by the compiler. In the older versions, you had to explicitly use @synthezie to let the compiler know that it has to generate the accessor methods. With the newer versions, it is not required. The compiler automatically generates the accessor methods.

    If you have declared the property as

    @property (nonatomic, retain) NSString *str;
    

    And if don't use @synthesize, then the ivar will be _str and the getter will be

    -(NSString)str
    

    and the setter will be

    -(void)setStr:(NSString *)newStr
    

    If you have mentioned the @synthesize specifically as

    @synthesize str = _myStr
    

    Then the ivar will be _mystr instead of _str.

    So inorder to access the property str, you have to use self.str or [self str]