支持变量不是为属性自动合成的

时间:2014-08-31 15:57:51

标签: objective-c xcode

在我的视图控制器的头文件中,我创建了一个属性:

@property(nonatomic) BOOL hasPhoto;

在我的实现文件中,我想覆盖它的setter,因此:

-(void)setHasPhoto:(BOOL)hasPhoto{
    _hasPhoto = hasPhoto;
    if(hasPhoto){
        //do something
    }
}

然而,当我尝试编译时,Xcode没有看到支持变量,它应该被命名为_hasPhoto并且不会编译。如果我手动合成它:

@synthesize hasPhoto = _hasPhoto;

有效。我做错了什么?

1 个答案:

答案 0 :(得分:0)

Clang(Xcode背后的编译器)只会在属性的接口中声明属性时为属性生成支持ivar - 否则为you need to synthesize it或自己实现属性的方法。如果属性在类的协议或类别中定义,它将为您生成ivar。我的猜测是你已经在协议中声明了属性,在这种情况下你需要使用@synthesize hasPhoto=_hasPhoto

// This is just a forward declaration of the protocol
@protocol MyProto;

@interface ZZZMyController : UIViewController<MyProto>

// This property will get an ivar automatically generated
@property (nonatomic) BOOL hasPhoto;

@end

@interface ZZZMyController(ExtraStuff)

// This property will NOT get an ivar automatically, you would need to synthesize it explicitly or create your own implementations of both methods
@property (nonatomic) BOOL categoryBool;

@end

@protocol MyProto <NSObject>

// This property will NOT get an ivar automatically either, you would need to synthesize it explicitly or create your own implementations of both methods
@property (nonatomic) protoBool;

@end

如果此答案无法解决您的问题,我建议您删除并重新安装Xcode。如果 不起作用,请提交bug report