Objective-C synthesize property name overriding

前端 未结 5 482
心在旅途
心在旅途 2020-12-08 08:26

I am trying to understand the purpose of the synthesize directive with property name overriding. Say that I have an interface defined as follow:



        
5条回答
  •  南方客
    南方客 (楼主)
    2020-12-08 08:52

    The advantage of having another name for the ivar than for the property is that you can easily see in the code when you are accessing one or the other - Andre K

    I'm not able to find a 'comment' button so I'm having to post as an 'answer'.

    Just wanted to expand on Andre's comment - by knowing when you are using the synthesized properties vs the vanilla variable, you know (especially in case of setters) when a variable is being retained/copied/released automatically thanks to your nice setter, vs being manipulated by hand.

    Of course if you are doing things right, you probably don't need the help of a setter to retain/release objects properly! But there can be other scenarios too where referring to your ivars as self.ivar instead of _ivar can be helpful, such as when you are using custom setters/getters instead of the default synthesized ones. Perhaps every time you modify a property, you also want to store it to NSUserDefaults. So you might have some code like this:

    @interface SOUserSettings : NSObject {
    
    BOOL _autoLoginOn;
    
    }
    
    @property (nonatomic, assign) BOOL autoLoginOn;
    
    @end
    
    @implementation SOUserSettings
    
    @synthesize autoLoginOn = _autoLoginOn;
    
    - (void)setAutoLoginOn:(BOOL)newAutoLoginOnValue {
    
       _autoLoginOn = newAutoLoginOnValue;
       [[NSUserDefaults standardUserDefaults] setBool:_autoLoginOn forKey:@"UserPrefAutoLoginOn"];
    }
    
    @end
    

    Note: This is just illustrative code, there could be a thousand things wrong with it!

    So now, in your code, if you have a line that says _autoLoginOn = YES - you know it's not going to be saved to NSUserDefaults, whereas if you use self.autoLoginOn = YES you know exactly what's going to happen.

    The difference between _autoLoginOn and self.autoLoginOn is more than just semantic.

提交回复
热议问题