- 当我写了两个页面:
AviewController和BviewController,并且我想在AviewController页面中使用到BviewController,在BviewController页面中使用到AviewController。 - 此时我需要在
AviewController.h中导入BviewController.h的头文件,在BviewController.h中导入AviewController.h的头文件,如下
- 在
BViewController.h导入AViewController.h:
#import "ViewController.h"
#import "BViewController.h"
NS_ASSUME_NONNULL_BEGIN
@interface AViewController : ViewController
@property (nonatomic, strong) BViewController* bViewController;
@end
- 在
AViewController.h导入BViewController.h:
#import "ViewController.h"
#import "AViewController.h"
NS_ASSUME_NONNULL_BEGIN
@interface BViewController : ViewController
@property (nonatomic, strong) AViewController* aViewController;
@end
此时会报错!!!

原因: 交叉编译,两个类的头文件相互引用是会报错误的,因为.h文件他是接口,在预编译的时候就会报错的。
如何修改? 使用@class
- 就是把原本头文件导入的代码
#import "BViewController.h"改为@class BViewController;即可
#import "ViewController.h"
@class BViewController;
NS_ASSUME_NONNULL_BEGIN
@interface AViewController : ViewController
@property (nonatomic, strong) BViewController* bViewController;
@end
总结如下:
- OC中两个类 A B,在 A 和 B的.m文件中相互#import对方的头文件没有问题。
- 但是在 A B的.h文件中相互引用对方的头文件#import,编译出错。
- 但是当A或者B是需要继承父类的和需要实现代理接口的时候,这种情况下需要在.h文件中引用对方的头文件的时候,如何避免编译不通过呢?
采用在将其中一个类的#import,改为@class,并将这个#import放到这个类的.m文件中去。










