具有合成只读属性的类的子类无法访问Objective-C中的实例变量

tacos_tacos_tacos

在超类中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

我想念什么?

谢尔盖·卡里尼琴科(Sergey Kalinichenko)

实例变量_pString所生产@synthesize私人MyClass您需要对其进行保护,以便MySubclass能够访问它。

_pString在的@protected部分添加一个ivar声明MyClass,如下所示:

@interface MyClass : NSObject {
    @protected
    NSString *_pString;
}

@property (nonatomic, strong, readonly) NSString *pString;

@end

现在,像往常一样合成访问器,您的变量将可以被您的子类访问。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章