具有合成readonly属性的类的子类无法访问Objective-C中的实例变量 [英] Subclass of class with synthesized readonly property cannot access instance variable in Objective-C

查看:226
本文介绍了具有合成readonly属性的类的子类无法访问Objective-C中的实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在超类 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中的实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆