What's the purpose of an ivar when a property exists?

前端 未结 3 1896
遥遥无期
遥遥无期 2020-12-03 03:10

The following doesn\'t complain at compilation nor runtime about no name ivar. So why is it so common to see an ivar and @property/@synthesize

3条回答
  •  無奈伤痛
    2020-12-03 03:48

    eman's answer is correct overall, but there is one reason to still declare ivars even in the new runtime: Apple discourages synthesized accessors in init and dealloc methods. Essentially, getters and setters are allowed to have side-effects other than just setting a variable. In particular, they could trigger KVO notifications. With an ivar to talk to, you can just send release and be done with it. But if all you have is a property, your only choice is to set it and hope you avoid any unfortunate interactions.

    I'm not sure how big a problem this is in practice, to be honest. I've just superstitiously avoided it, even though I secretly doubt it would cause a problem in most cases. But Apple does make a point of this in the docs, so I assume there is some reason to be concerned.

提交回复
热议问题