为什么在 AppDelegate.h 中为 ViewController 使用 @class 而不是 #import? [英] Why @class instead of #import for ViewController in AppDelegate.h?

查看:56
本文介绍了为什么在 AppDelegate.h 中为 ViewController 使用 @class 而不是 #import?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Objective C 中有一个基本的最佳实践问题.我理解 @class#import 之间的区别,但我不明白为什么默认的 Apple Xcode 模板这样做:

I have a basic best-practices question in Objective C. I understand the difference between @class and #import but I do not understand why the default Apple Xcode templates do this:

AppDelegate.h:

AppDelegate.h:

@class ViewController;

.m:

#import "ViewController.h

当您可以将后者 #import 放在 .h 中,而在 中不提及 ViewController 时.m,从而简化了 1 行代码.

When you could instead just put the latter #import in the .h and leave mention of ViewController out of the .m altogether, thereby simplifying by 1 line of code.

当然,节省 1 行代码不是问题,我只是好奇为什么要这样做?

Of course, saving 1 line of code is not the issue, I'm just curious why it's being done this way?

推荐答案

@class ViewController; 是一个前向声明,所以编译器知道什么名称 ViewController 应该是什么意思.关键是在头文件中尽量少使用 #import 以加快编译速度.

The line @class ViewController; is a forward declaration so the compiler has an idea what the name ViewController should mean. The point is to try to do as few #import's in a header file as possible to speed up compiling.

想象一个文件 a.h 执行 #import "b.h".现在每个导入 a.h 的文件也会自动导入 b.h,这增加了编译器必须做的工作量.通过使用前向声明,通常可以避免此类额外的导入,从而避免编译器的额外工作.

Imagine a file a.h which does #import "b.h". Now every file that imports a.h automatically also imports b.h which increases the amount of work the compiler has to do. By using forward declarations one can often avoid such additional imports and thus avoid the additional work for the compiler.

项目越大,类层次结构和依赖关系越复杂,这些 #import 就会成为问题.因此,养成尽可能使用前向声明的习惯是个好主意.

The bigger the project and the more complex the class hierarchies and dependencies become the more these #imports can become an issue. So it's a good idea to develop a habit of using forward declarations where possible.

在评论之后,另一个重要的用例浮出水面:解决循环依赖.例如,如果 A 类想要引用 B 类,反之亦然,则必须先定义一个类.但是因为他们需要了解对方,所以我们有一个悖论.是这样解决的:

After the comments, another important use-case surfaced: to resolve cyclic dependencies. For example, if class A wants to reference class B and vice versa, one has to be defined before the other. But because they need to know the other we have a paradox. It's solved like this:

// Tell the compiler: B will be a class type.
@class B;

// Now we can define A, the compiler has enough
// information to know what B means.
@interface A : NSObject {
    B *b;
}
@end

// Since A is now defined, we can define B.
// Cycle is resolved.
@interface B : NSObject {
    A *a;
}
@end

这篇关于为什么在 AppDelegate.h 中为 ViewController 使用 @class 而不是 #import?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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