且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么在Objective-C的头文件中定义实例变量

更新时间:2022-04-21 22:48:51

原因是它可以为子类计算变量的偏移量.

The reason is so it can calculate offsets of variables for subclasses.

@interface Bird : NSObject {
    int wingspan;
}
@end
@interface Penguin : Bird {
    NSPoint nestLocation;
    Penguin *mate;
}
@end

在不了解"Bird"类的结构的情况下,"Penguin"类无法计算其字段从结构开始处的偏移量.企鹅的结构看起来像这样:

Without knowing the structure of the "Bird" class, the "Penguin" class can't calculate the offset of its fields from the beginning of the structure. The penguin structure looks kind of like this:

struct Penguin {
    int refcount; // from NSObject
    int wingspan; // from Bird
    NSPoint nestLocation; // from Penguin
    Penguin *mate; // from Penguin
}

这具有副作用:如果更改库中类的大小,则会中断链接到该库的应用程序中的所有子类.新属性可解决此问题.

This has a side effect: if you change the size of a class in a library, you break all the subclasses in apps that link to that library. The new properties work around this problem.