如果宣布我自己的吸气剂并且iVar不被认可二传手 [英] iVar not recognized if declaring my own getter & setter

查看:72
本文介绍了如果宣布我自己的吸气剂并且iVar不被认可二传手的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

不使用getter AND setter的属性

这是我面临的问题:我正在使用iOS 6.我在头文件中声明了一个属性:

this is the problem I'm facing: I'm using iOS 6. I declare a property in the header file:

@property (nonatomic) CGFloat scale;

然后在实现中,我创建了我自己的getter / setter,如下所示:

Then in the implementation, I create my own getter/setter like this:

#define DEFAULT_SCALE 0.90    

- (void)setScale:(CGFloat)scale
{
    if(_scale != scale) {
        _scale = scale;
        [self setNeedsDisplay];
    }
}

- (CGFloat) scale
{
    if(!_scale) {
        return DEFAULT_SCALE;
    } else {
        return _scale;
    }
}

问题是编译器无法识别_scale。我得到错误使用未声明的标识符'_scale'。
如果我删除了getter或setter,那么它工作正常,但我不能同时保留两者。如果我这样做,我必须添加 @synthesize scale = _scale 以避免错误。有人可以解释原因吗?

the problem is that _scale is not recognized by compiler. I get error "Use of undeclared identifier '_scale'. If I remove the getter or the setter, then it works fine, but I can't keep both. If I do, I have to add @synthesize scale = _scale to avoid the error. Can someone explain why?

谢谢

推荐答案

如果你要使用自己的setter /你需要在 @interface 中声明实例变量getter:

You need to declare the instance variable in the @interface if you're going to use your own setter/getter:

@interface MyClass : NSObject
{
    CGFloat _scale;
}
...
@end

编辑(之后) OP问题):

EDIT (after OP question):

你的特定实现肯定会产生影响(它们不是简单的getter / setter方法,因为它们会起到副作用的作用)。但我认为如果你想要定位32位OSX,那么声明你的变量总是一个好主意,因为运行时不支持自动声明的实例变量。

Your particular implementation certainly makes a difference (they aren't simple getter/setter methods as they do something as a side-effect). However I think it's always a good idea to declare your variables and absolutely necessary if you want to target 32-bit OSX, as the runtime doesn't support auto-declared instance variables.

这篇关于如果宣布我自己的吸气剂并且iVar不被认可二传手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆