如何克服#import循环?

时间:2015-08-05 10:56:46

标签: ios objective-c

想象一下,我有两个标头文件:SomeFileA.hSomeFileB.h

SomeFileA.h包括SomeFileB.hSomeFileB.h包含SomeFileA.h

这会创建一个循环并混淆编译器。我们怎么能克服这个?

1 个答案:

答案 0 :(得分:8)

你应该“转发声明”你的课程。这告诉编译器该类是否存在,但不需要实际导入它。

SomeFileA.h

@class SomeFileB  // <-- This "forward declares SomeFileB"
@interface SomeFileA

@property (nonatomic, strong) SomeFileB *someFileB;
...
@end

SomeFileA.m

#import "SomeFileB.h"
@implementation SomeFileA
...
@end

同样的事情,但在SomeFileB的另一种方式

SomeFileB.h

@class SomeFileA  // <-- This "forward declares SomeFileA"
@interface SomeFileB

@property (nonatomic, strong) SomeFileA *someFileA;
...
@end

SomeFileB.m

#import "SomeFileA.h"
@implementation SomeFileB
...
@end

如果您不在标题中使用某个类,则无需转发声明它。

@interface SomeFileA
//I took out the property for SomeFileB.. no need for the @class anymore.
...
@end