Reason to use ivars vs properties in objective c

前端 未结 5 1432
说谎
说谎 2020-11-27 05:50

I have been unable to find any information on this topic and most of what I know about it has come by complete accident (and a few hours of trying to figure out why my code

5条回答
  •  春和景丽
    2020-11-27 06:22

    You can just use @property and @synthesize without declaring the ivars, as you suggested. The problem above is that your @synthesize mapped the property name to a new ivar that is generated by the compiler. So, for all intents and purposes, your class definition is now:

    @interface Test : NSObject {
    int timesPlayed;
    int highscore;
    int _timesPlayed;
    int _highscore;
    }
    ...
    @end
    

    Assigning a value directly to the ivar timesPlayed will never show up if you access it via self.timesPlayed since you didn't modify the correct ivar.

    You have several choices:

    1 Remove the two ivars you declared in your original post and just let the @property / @synthesize dynamic duo do their thing.

    2 Change your two ivars to be prefixed by an underscore '_'

    3 Change your @synthesize statements to be:

    @implemenation Test
    @synthesize timesPlayed;
    @synthesize highscore;
    
    ...
    

提交回复
热议问题