Objective-C:@interface之前的@class指令? [英] Objective-C: @class Directive before @interface?

查看:190
本文介绍了Objective-C:@interface之前的@class指令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个类声明之间有什么区别?我不明白为什么在这里使用@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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆