【发布时间】:2012-08-26 12:28:38
【问题描述】:
从 xcode 4.4 开始,您不再需要 @synthesize 属性 (see here),编译器会为您完成。那么,为什么编译器会抱怨
使用未声明的标识符 _aVar
在我的viewDidLoad方法ViewControllerSubclass中:
@interface ViewController : UIViewController
@property (assign, nonatomic) int aVar;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.aVar = 5;
NSLog(@"Super value: %d", _aVar);
}
@end
@interface ViewControllerSubclass : ViewController
@end
@interface ViewControllerSubclass ()
@property (assign, nonatomic) int aVar;
@end
@implementation ViewControllerSubclass
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"Subclass value: %d", _aVar);
}
@end
如果我将所有内容都移到一个文件而不是 4 个用于各自接口和实现的单独文件中,编译器反而会抱怨 _aVar 是私有的。但是 _aVar 应该已经在我的ViewControllerSubclass 中自动合成了。
如果我将初始属性声明移至类扩展名,则仍将所有内容保存在 1 个文件中:
@interface ViewController ()
@property (assign, nonatomic) int aVar;
@end
构建仍然失败,说 _aVar 是私有的。
如果我返回 4 个文件设置为相应的接口和实现 xcode 构建甚至没有警告。
如果我再运行代码:
[[[ViewControllerSubclass alloc] init] view];
以上示例中的日志语句打印出以下内容:
超值:0
子类值:5
NSLog(@"Super value: %d", _aVar); 产生0 的结果是有道理的,因为这个变量应该是超类的私有变量。但是,为什么NSLog(@"Subclass value: %d", _aVar); 会产生5 的结果??
这一切都很奇怪。
【问题讨论】:
-
据我了解,这是 Apple LLVM 4.0 编译器的一个功能,而不是 Xcode IDE。您在项目中使用什么编译器?
-
可以,但是xcode4.4默认使用这个编译器。
-
那么构建但生成奇怪日志语句的配置是您在超类的公共接口和子类的扩展中声明属性的配置?
-
不,唯一构建的“配置”是在超类和子类的类扩展中声明两个属性的配置。