问题描述
我可以理解在头文件的@interface中定义函数,但是为什么要使用实例变量?实例变量不应该是私有的,只能通过消息访问吗?
I can understand defining the functions in the @interface of the header file, but why the instance variables? Shouldn't the instance variables be private, only accessible through messages?
推荐答案
原因是它可以为子类计算变量的偏移量.
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.
这篇关于为什么在Objective-C的头文件中定义实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!