iOS automatic @synthesize without creating an ivar

后端 未结 3 1947
北恋
北恋 2020-12-09 10:59

If I have a @property which I didn\'t want to have backed via an ivar I simply omitted the @synthesize and had manual getters which re

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-09 11:37

    In my working with this, I've noticed the following behavior.

    1. If you have a readwrite property, don't have a @synthesize, have a getter and don't have a setter, then it will generate the iVar.
    2. If you have a readwrite property, don't have a @synthesize, don't have a getter, and have a setter, then it will generate the iVar.
    3. If you have a readwrite property, don't have a @synthesize and have both a getter and a setter, then it will not generate the iVar.
    4. If you have a readonly property, don't have a @synthesize and don't have a getter, then it will generate the iVar.
    5. If you have a readonly property, don't have a @synthesize and have a getter, then it will not generate the iVar.

    From this, I think the general rule is that if you don't have a @synthesize, and have all the methods needed to fully implement the property, then it's assumed to be dynamic and doesn't generate the iVar.

    At any rate, if you want to ensure that an iVar is not generated then declare it as @dynamic.


    Clarification on @dynamic

    From Declared Properties in The Objective-C Programming Language:

    You use the @dynamic keyword to tell the compiler that you will fulfill the API contract implied by a property either by providing method implementations directly or at runtime using other mechanisms such as dynamic loading of code or dynamic method resolution.

    To me this reads like it OK to mark a property as @dynamic even when you are directly implementing the getter and setter.

提交回复
热议问题