iOS: Objective-C creating class property error: Use of undeclared identifier

时光怂恿深爱的人放手 提交于 2019-12-02 09:11:35

Class properties don't get synthesized in Objective-C. You have to provide your own backing variable and your own getter/setter:

static NSString *_myProperty = nil;

+ (NSString *)myProperty {
    if (!_myProperty) {
        _myProperty = [NSString new];
    }

    return _myProperty;
}

+ (void)setMyProperty:(NSString *)myProperty {
    _myProperty = myProperty;
}

Class properties and never auto-synthesised, the getter and/or setter must be implemented, and no backing variable is automatically created for them.

If your property needs a variable you must declare one, use a static global in the implementation file - that is effectively a "class variable" in Objective-C. Alternatively if you only require a getter you can declare a static variable local to the getter itself, further reducing its visibility and keeping the getter and variable together as a package.

HTH

In fact, class property is not a member of a class. So it will be created at once and all instances will use this one. So there is nothing to synthesize.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!