这两个类声明有什么区别?我不明白为什么在这里使用@class。谢谢。
@class TestClass;
@interface TestClass: UIView {
UIImage *image1;
UIImage *image2;
}
和
@interface TestClass: UIView {
UIImage *image1;
UIImage *image2;
}
最佳答案
@class
的存在是为了打破循环依赖。假设你有 A 类和 B 类。
@interface A:NSObject
- (B*)calculateMyBNess;
@end
@interface B:NSObject
- (A*)calculateMyANess;
@end
鸡;遇见蛋。这永远无法编译,因为 A 的接口(interface)取决于 B 的定义,反之亦然。
因此,可以使用 @class
来修复它:
@class B;
@interface A:NSObject
- (B*)calculateMyBNess;
@end
@interface B:NSObject
- (A*)calculateMyANess;
@end
@class
有效地告诉编译器这样的类存在于某处,因此,声明为指向所述类的实例的指针是完全有效的。但是,您不能在类型仅定义为 @class
的实例引用上调用方法,因为编译器没有可用的其他元数据(我不记得它是否恢复调用是否通过 id
将站点评估为调用)。
在您的示例中,@class
是无害的,但完全没有必要。
关于Objective-C:@interface 之前的@class 指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10019961/