可以使用 Objective-C 的前向声明(forward declaration)来实现不使用导入头文件的类。具体步骤如下:
在需要使用该类的文件中进行 forward declaration,语法为:@class className;
在使用该类的地方进行调用。
例如,实现不使用导入头文件的 UIViewController 类:
// ViewController.h 文件中 @class SomeOtherClass;
@interface ViewController : UIViewController
@property (nonatomic, strong) SomeOtherClass *someObject;
@end
// ViewController.m 文件中 #import "SomeOtherClass.h"
@implementation ViewController
(void)viewDidLoad { [super viewDidLoad];
self.someObject = [[SomeOtherClass alloc] init]; }
@end
通过前向声明,我们不需要在 ViewController.h 文件中导入 SomeOtherClass.h 文件,从而实现了不使用导入头文件的类。