以下内容似乎很简单.有一个带有 ivar 的超类,以及一个访问(@protected)超类 ivar 的子类:
The following seems simple enough. There's a superclass with an ivar, and a subclass which accesses the (@protected) superclasses ivar:
// Testclass.h
@interface TestClass : NSObject {
NSString *testIvar;
}
@end
//TestClass.m
@implementation TestClass
@end
//TestSubclass.h
@interface TestSubClass : TestClass {
}
@property (nonatomic, retain) NSString *testProperty;
- (void) testMethod;
@end
//TestSubclass.m
#import "TestSubClass.h"
@implementation TestSubClass
@synthesize testProperty;
- (void) testMethod{
NSLog(@"The value was: %@", testIvar);
}
@end
简单而正确——看起来足够了.但是,尝试编译(对于 iOS 4.2 SDK,使用 GCC 4.2)会产生指向 NSLog 行的错误:'testIvar undeclared'.
Simple and correct-seeming enough. However, attempting to compile (for iOS 4.2 SDK, with GCC 4.2) produces this error pointing to the NSLog line: 'testIvar undeclared'.
我是 Objective-C 的新手,但我一生都无法理解为什么这应该是一个错误.注释掉 testProperty 的东西,它就可以编译了.似乎在子类中添加一个综合属性,没有对应的 ivar,实际上是在隐藏一个不相关的超类 ivar.
I'm new to Objective-C, but can't for the life of me see why this should be an error. Comment out the testProperty stuff, and it compiles OK. It seems like adding a synthesized property in a subclass, without a corresponding ivar, is actually hiding an unrelated superclass ivar.
谁能告诉我这里发生了什么?与此相关的是,编译错误是否可以预见?(预见到它会为我节省一些时间和挫败感).
Can anyone enlighten me as to what's happening here? Relatedly, was the compilation error foreseeable? (Foreseeing it would have saved me some time and frustration).
LLVM编译源码不报错,切换到LLVM:Select target → Get Info → Build → C/C++ Compiler Version → LLVM 1.5.根据我有限的经验,无论如何它是一个更好的编译器.不知道为什么 GCC 会这样做——有趣的问题.
LLVM compiles the source without complaints, switch to LLVM: Select target → Get Info → Build → C/C++ Compiler Version → LLVM 1.5. From my limited experience it’s a better compiler anyway. No idea why GCC behaves the way it does – interesting catch.
这篇关于为什么没有相应 ivar 的子类 @property 隐藏超类 ivar?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!