Objective-C:@interface 之前的@class 指令? [英] Objective-C: @class Directive before @interface?
问题描述
这两个类声明有什么区别?我不明白为什么在这里使用@class.谢谢.
What is the difference between these two class declarations? I don't understand why @class is utilized here. Thanks.
@class TestClass;
@interface TestClass: UIView {
UIImage *image1;
UIImage *image2;
}
和
@interface TestClass: UIView {
UIImage *image1;
UIImage *image2;
}
推荐答案
@class
的存在是为了打破循环依赖.假设您有 A 类和 B 类.
@class
exists to break circular dependencies. Say you have classes A and B.
@interface A:NSObject
- (B*)calculateMyBNess;
@end
@interface B:NSObject
- (A*)calculateMyANess;
@end
鸡肉;遇见蛋蛋.这永远无法编译,因为 A 的接口取决于 B 的定义,反之亦然.
Chicken; meet Egg. This can never compile because A's interface depends on B being defined and vice-versa.
因此,它可以通过使用@class
来修复:
Thus, it can be fixed by using @class
:
@class B;
@interface A:NSObject
- (B*)calculateMyBNess;
@end
@interface B:NSObject
- (A*)calculateMyANess;
@end
@class
有效地告诉编译器这样的类存在于某处,因此,声明指向所述类的实例的指针是完全有效的.但是,您不能在类型仅定义为 @class
的实例引用上调用方法,因为编译器没有可用的其他元数据(我不记得它是否恢复调用网站是否通过 id
被评估为调用).
@class
effectively tells the compiler that such a class exists somewhere and, thus, pointers declared to point to instances of said class are perfectly valid. However, you couldn't call a method on an instance reference whose type is only defined as an @class
because there is no additional metadata available to the compiler (I can't remember if it reverts the call site to being evaluated as a call through id
or not).
在您的示例中,@class
是无害的,但完全没有必要.
In your example, the @class
is harmless, but entirely unnecessary.
这篇关于Objective-C:@interface 之前的@class 指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!