Error accessing generated ivars when I override setters and getters in Modern Objective-C

后端 未结 3 1278
猫巷女王i
猫巷女王i 2021-01-01 13:57

I know now the new Objective-C compiler lets you not need to synthesize your properties anymore. I have one file that has two classes in it. My .h for a simple helper clas

相关标签:
3条回答
  • 2021-01-01 14:44

    If you override both the setter and the getter, the compiler will not automatically create the instance variable for you anymore. You can add it to your class implementation like so:

    @implementation ClassName {
        ViewFrameModel *_viewFrameModel;
    }
    ...
    @end
    
    0 讨论(0)
  • 2021-01-01 14:45

    To summarize the answers:

    If you override both the setter and the getter, the compiler will not create the instance variable for you.

    Why? In that case, the compiler assumes that the property is dynamic: that it might be a property that relies on other properties for storage / computation, or that it will be created in other ways, for example, at runtime using Objective-C runtime functions.

    To help the compiler understand the situation better there are two potential solutions:

    @implementation Class {
    @synthesize property = _property;
    ...
    @end
    

    or

    @implementation Class {
        PropertyClass *_property;
    }
    ...
    @end
    
    0 讨论(0)
  • 2021-01-01 14:54

    Here is the results of some testing I did last year: iOS automatic @synthesize without creating an ivar.

    In short, you need to use @synthesize or declare an iVar explicitly.

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