【转】ios中@class和 #import 的使用时机

代码中会发现有部分#import操作写在m文件中,而h文件仅仅使用@class进行声明,为什么不直接把#import放到h文件中呢?

这是因为h文件在修改后,所有import该h文件的所有文件必须重 新build,因此,如果把#import写在h文件中,import该h文件的文件也就会产生不必要的编译,增加编译时间,特别是在项目文件多的情况 下。想象一下,如果只是修改一个h文件而导致上百个文件不必要的编译,那是一件多么让人纠结的事情。。。

对于@class只是告诉编译器有这个class,请不要报错或警告,因此不会给编译造成影响。
什么时候用@class这种方式声明比#import好呢?
stackoverflow上的高手们给了不少建议:
Randy Marsh:
When I develop, I have only three things in mind that never cause me any problems.
Import super classes
Import parent classes (when you have children and parents)
Import classes outside your project (like in frameworks and libraries)
For all other classes (subclasses and child classes in my project self), I declare them via forward-class.

Justin:
Simple answer: You #import or #include when there is a physical dependency. Otherwise, you use forward declarations (@class MONClass ,struct MONStruct , @protocol MONProtocol ).
Here are some common examples of physical dependence:
Any C or C++ value (a pointer or reference is not a physical dependency). If you have aCGPoint as an ivar or property, the compiler will need to see the declaration ofCGPoint .
Your superclass.
A method you use.

在 Objective-C 中,#import 被当成 #include 指令的改良版本来使用。
除此之外,#import 确定一个文件只能被导入一次,这使你在递归包含中不会出现问题。

使用哪一个还是由你来决定。一般来说,在导入 Objective-C 头文件的时候使用 #import,包含 C 头文件时使用 #include。
比如:
#import <foundation /Foundation.h>
#include <mach /mach.h>

@class是用来做类引用的
@class就是告诉编译器有这么一个类,至于类的定义是啥不知道
@class一般用于头文件中需要声明该类的某个实例变量的时候用到,在m文件中还是需要使用#import

举个例子说明:
在ClassA.h中
#import ClassB.h 相当于#include整个.h头文件。如果有很多.m文件#import ClassA.h,那么编译的时候这些文件也会#import ClassB.h增加了没必要的#import,浪费编译时间。在大型软件中,减少.h文件中的include是非常重要的。
如果
只是@class ClassB 那就没有include ClassB.h。仅需要在需要用到ClassB的ClassA.m文件中 #import ClassB.h
那么什么时候可以用@class呢?
如果ClassA.h中仅需要声明一个ClassB的指针,那么就可以在ClassA.h中声明
@ClassB
...
ClassB *pointer;

ps:A import B,B也需要A的时候, 就在B.h中@classA,然后在B.m中importA。

原文地址:https://www.cnblogs.com/willbin/p/3142203.html