Reason to use ivars vs properties in objective c

前端 未结 5 1456
说谎
说谎 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:21

    In your example, @synthesize timesPlayed = _timesPlayed; creates a new ivar called _timesPlayed and the property refers to that ivar. timesPlayed will be an entirely separate variable with no relation whatsoever to the property. If you just use @synthesize timesPlayed; then the property will refer to timesPlayed.

    The purpose of the underscore convention is to make it easier to avoid accidentally assigning directly to an ivar when you want to be doing it through the property (i.e. through the synthesized setter method). However, you can still acces _timesPlayed directly if you really want to. Synthesizing a property simply auto-generates a getter and setter for the ivar.

    In general you do not need to declare an ivar for a property, although there may be special cases where you would want to.

提交回复
热议问题