【问题标题】:Backing variable not automatically synthesized for property支持变量不会为属性自动合成
【发布时间】:2014-08-31 15:57:51
【问题描述】:

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

@property(nonatomic) BOOL hasPhoto;

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

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

但是,当我尝试编译时,Xcode 看不到支持变量,它应该命名为 _hasPhoto 并且无法编译。如果我手动合成:

@synthesize hasPhoto = _hasPhoto;

它有效。我做错了什么?

【问题讨论】:

  • 你是否也重写了 getter 方法?那么这是stackoverflow.com/questions/13817562/…的副本。
  • @MartinR 不,我没有覆盖吸气剂。问题中的代码是所有(相关)代码。
  • 这很奇怪。您的代码编译对我来说没有问题。你能展示一个 .h 和 .m 文件的(最小的)独立示例吗?
  • Xcode 的哪个版本?您使用的是 5.0 之前的版本吗?
  • 出于好奇,如果在实现中添加@synthesize hasPhoto=_hasPhoto;,编译是否正常?

标签: objective-c xcode


【解决方案1】:

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

【讨论】:

  • 不幸的是,事实并非如此。该属性在具有许多其他属性的头文件中的常规类接口中定义,没有问题。它不在 M 文件中,不在协议声明中,也不在扩展/类别中。我认为重新安装 Xcode 不会有太大变化(我已经清除了派生数据并清理了构建文件夹,重新启动了 Xcode 等),我想我会提交一个错误报告。
猜你喜欢
  • 2014-08-25
  • 2011-05-03
  • 1970-01-01
  • 1970-01-01
  • 2016-09-13
  • 1970-01-01
  • 2014-10-22
  • 1970-01-01
相关资源
最近更新 更多