子类中没有支持实例变量

No backing instance variables in subclass

我有一个 class 子class 来自 NSObject - Rectangle,它子class - Square.

在Rectangle.h我有属性:

@property int height, width;

我在实现文件中手动声明支持变量:

@implementation Rectangle
{
    int _width;
    int _height;
}

我的问题是:在我直接继承自 Rectangle - @interface Square : Rectangle 的 subclass Square 中,我想使用在 superclass 中声明的变量。但是,我无法通过 _width_height 看到它们,只能相应地调用 getter 方法 - self.width[self setWidth:x]

是的,使用 getter 方法没有问题,但为什么我不能使用合成的支持变量(在我的例子中是手动声明的)?它是否以某种方式受到 child class 的保护?

您只是在头文件中声明它们。就您的子类而言,该头文件代表其父类的接口。正式地,它不知道私有实例变量,只知道 public 属性。

是的,它们是私有的,因此可以 removed/renamed 这会破坏子类。即使它们是综合支持变量,您仍然不知道确切的实现是什么。

如果您真的需要在子类中访问它们,您可以创建一个单独的 header and/or 使用 @private

如果你想让你的子类直接访问变量(类似于public或在C++中受保护),你可以在接口块中声明它们:

@interface MyClass : NSObject {
    NSInteger _asdf;
}

在 Objective-C 非脆弱实例变量增强之前,声明实例变量的能力仅在 @interface 块中可用,并且这些变量随处可用。也可以使用 @private 指令锁定变量。

所以,回答你的问题:在@interface 块中声明变量将允许你直接访问它们,但我会谨慎行事,因为现在可以隐藏实现细节的语言要好得多。

如果您想在子类中使用在超类中创建的 ivar,请在超类的 .h 文件(而不是属性)中声明这些 ivar。此外,您不应该 "manually declare" .m 文件中的支持实例变量,因为您会自动获取这些变量。

@interface Rectangle : NSObject {
    int height;
    int width;
}