问题描述
在超类 MyClass
中:
@interface MyClass : NSObject
@property (nonatomic, strong, readonly) NSString *pString;
@end
@implementation MyClass
@synthesize pString = _pString;
@end
在子类 MySubclass
@interface MySubclass : MyClass
@end
@implementation MySubclass
- (id)init {
if (self = [super init]) {
_pString = @"Some string";
}
return self;
}
问题是编译器不认为 _pString
是 MySubclass
的成员,但我在 MyClass
中访问它没有问题。
The problem is that the compiler doesn't think that _pString
is a member of MySubclass
, but I have no problem accessing it in MyClass
.
我缺少什么?
推荐答案
实例变量 _pString
由 @synthesize
生成私人到 MyClass
。您需要将 protected 设为 MySubclass
才能访问它。
The instance variable _pString
produced by @synthesize
is private to MyClass
. You need to make it protected in order for MySubclass
to be able to access it.
在 MyClass $的
@protected
部分添加 _pString
的ivar声明c $ c>,像这样:
Add an ivar declaration for _pString
in the @protected
section of MyClass
, like this:
@interface MyClass : NSObject {
@protected
NSString *_pString;
}
@property (nonatomic, strong, readonly) NSString *pString;
@end
现在像往常一样合成访问者,你的变量将您的子类可以访问。
Now synthesize the accessors as usual, and your variable will become accessible to your subclass.
这篇关于具有合成readonly属性的类的子类无法访问Objective-C中的实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!