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

前端 未结 3 1887
遥遥无期
遥遥无期 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.

    0 讨论(0)
  • 2020-12-03 03:51

    Synthesized ivars (the ability to not manually declare ivars) are a feature of the new Objective-C runtime, which still isn't being used on all systems. For 32-bit Macs (and, until recently, the iPhone simulator), you have to manually declare ivars. If you're only targeting systems with the new runtime, there's no reason to manually declare ivars.

    0 讨论(0)
  • 2020-12-03 04:07

    Two not-so-good-but-necessary reasons to make sure properties are backed up by ivars:

    1. For some reason the XCode debugger doesn't show properties that don't have corresponding ivars explicitly declared.
    2. It seems to me that under some circumstances using @property without an ivar can hide other ivars, resulting in compilation errors (see Why does a subclass @property with no corresponding ivar hide superclass ivars? )

    Unless I've got the wrong ends of a couple of sticks here, I think the use of @property without explicit ivars may lead to annoyances not warranted by the convenience.

    0 讨论(0)
提交回复
热议问题