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

谁说我不能喝 提交于 2019-12-02 16:24:36

问题


I'm trying to use class property following this example. But I'm getting the following error:"Use of undecleared identifier '_myProperty'".

Here is my implementation:

@interface myClass()

@property (class,strong,nonatomic) NSString *myProperty;

@end


+ (NSString*)myProperty
{
    if (!_myProperty) {

    }
    return [NSString new];
}

Why I'm getting this error? or any of you knows a work around this?

I'll really appreciate your help


回答1:


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;
}



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/45513816/ios-objective-c-creating-class-property-error-use-of-undeclared-identifier

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