为什么在.h文件中使用前向声明而不是#import? [英] why use forward declaration rather than #import in .h file?

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

问题描述

我是初学的iOS / ObjectiveC编码器,我正在尝试理解一些细节,而不是愚蠢地遵循我看到的示例代码。

I'm a beginner iOS/ObjectiveC coder and am trying to understand some details rather than just dumbly following the example code I see.

我想我得到了.h文件中前向声明的要点:它告诉编译器指定的类是稍后定义的播放器 - 然后在.m文件中导入标题。

I think I get the gist of a forward declaration in a .h file: it tells the compiler that the specified class is a "player to be defined later" - and then the header is imported in the .m file.

我不明白为什么不只是在引用类的头中导入类头,而不是使用前向声明?我对#import的理解是它不会多次导入标题(就像#include一样 - 这需要if_def的东西)。

What I don't understand is why not just import the class header in the header where the class is referenced, rather than use a forward declaration? My understanding of #import is it won't import the header more than once (as would #include - which necessitates the if_def stuff).

我是否全都错了?

推荐答案

使用正向引用的一个原因是编译器速度。标头可能包含在许多其他文件中,这些文件可能不需要头文件中包含的定义。由于包含的文件包含在预处理器中,因此包含大量包含文件或包含大量文件会大大增加编译器必须处理的代码行。

One reason to use forward references is compiler speed. A header may be included in many other files and those files may not need the definitions included in your header file. Since included files are included by the preprocessor, having a lot of includes or large included files can greatly increase the lines of code that the compiler has to deal with.

你可以通过使用Xcode中的preprocess命令来查看预处理器的输出。通过在标头中正向声明类,您将删除头文件中包含的所有代码。

You can see this yourself by using the preprocess command in Xcode to see the output of the preprocessor. By forward declaring classes in the header you are removing all of the code that would have been included by the header file.

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

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