Objective c 为什么我不能访问超类中带有属性的实例变量集?
我得到了以下对象:Objective c 为什么我不能访问超类中带有属性的实例变量集?,objective-c,Objective C,我得到了以下对象: @interface Foo : NSObject @property (readonly, strong) NSString *someVar; @end @implemtation Foo @sythensize someVar = _someVar; @end 然后我将其子类化: @interface Bar : Foo -(id)initWithString:(NSString *)string; @end @implementation Bar -(id)in
@interface Foo : NSObject
@property (readonly, strong) NSString *someVar;
@end
@implemtation Foo
@sythensize someVar = _someVar;
@end
然后我将其子类化:
@interface Bar : Foo
-(id)initWithString:(NSString *)string;
@end
@implementation Bar
-(id)initWithString:(NSString *)string {
_someVar = string;
}
@end
但是我得到了一个“使用未声明的标识符”\u someVar“。。。。。为什么Bar不知道foo的实例变量_someVar?始终使用getter/setter。低级别/直接访问仅在寻求十亿分之一秒的性能改进时才合适,在这种情况下,我怀疑您是否应该完全放弃Obj-C,转而只使用C 我是这样做的:
@synthesize someVar;
-(id)initWithString:(NSString *)string {
self.someVar = string;
}
或者,如果我有很好的理由不使用访问器方法。我根本不用@synthetic
另外,在最新版本的Xcode中,您可以跳过
@synthetic
行。可能的重复,密切相关:,这不是“不安全”,这是不可能的。编译器不允许你这么做。这就是问题的关键所在。我所说的“不安全”是指你不应该在任何常见的代码情况下使用这种做法,即使是在它可以工作的情况下。我更新了我的答案,以便更清楚地解释。我明白了。。我的模式通常是只读属性,我知道这些属性永远不会改变,只是在初始化实例时直接设置它们的实例变量,这样,我就不必担心其他对象会更改其中一个属性的值……然后在公共@interface
中将其声明为只读,并使用第二个私有@interface
将其声明为读/写。通常情况下,第二个接口是“无名”的,并且与@实现位于同一个文件中:不确定是否要从子类写入这些接口,也许可以更新您的问题以询问这个问题?