您是否将#import放在.h或.m文件中? [英] Do you put #import s in .h or .m files?
问题描述
我想知道Objective-C风格.
I wonder about Objective-C style.
我有FooClass.[hm],它的实现依赖于BarClass.[hm](尽管不是它的接口).我可以直接在FooClass.m中或直接通过FooClass.h #import "BarClass.h"
.我想知道这样做的共同选择.
I have FooClass.[hm] that depends on BarClass.[hm] for its implementation (though not for its interface). I can #import "BarClass.h"
either directly in FooClass.m or indirectly through FooClass.h. I wonder about the common choice for this.
推荐答案
您应始终 #import
个其他类在您的.m
文件中.
You should ALWAYS #import
other classes in your .m
file.
如果它们碰巧也是您的类的成员,则可以在.h
文件中转发声明它们(通过使用@class
指令).
If they happen to also be members of your class, you can forward declare them (by using the @class
directive) in your .h
file.
之所以这样做,是因为当您#import
一个.h
文件时,您只想导入声明,而不是定义.通过使用@class
并且仅在.m
文件中使用#import
,您将a)减少开销,并且b)使代码更简洁.
The reason for doing this is because when you #import
a .h
file, you only want to import declarations, not definitions. By using @class
and only #import
ing in .m
files, you are a) reducing overhead and b) makes for cleaner code.
马特·加拉格尔(Matt Gallagher)指出了您应该采用这种方式的另一个原因:
Another reason you should do it this way was pointed out by Matt Gallagher:
头文件中的前向声明背后的原因是,它避免了不必要的依赖关系.即想象B.h向前声明A和B.m进口A.h.然后想象C.m,D.m,E.m和F.m导入B.h.完成所有这些操作后,A.h发生变化.由于A仅在B.h中向前声明,因此仅B.m需要重建.如果没有前向声明,则如果A发生更改,则C.m,D.m,E.m和F.m都将需要重建.
The reasoning behind forward declarations in header files is that it avoids unnecessary dependencies. i.e. Imagine B.h forward declares A and B.m imports A.h. Then imagine C.m, D.m, E.m and F.m import B.h. After all this is done, A.h changes. Since A is only forward declared in B.h, only B.m needs to rebuild. Without forward declarations, C.m, D.m, E.m and F.m would all need to be rebuild if A changes
示例:
.h
文件:
.h
file:
@class BarClass;
@interface FooClass : NSObject
...
@end
.m
文件
.m
file
#import "BarClass.h"
@implementation FooClass
...
@end
这篇关于您是否将#import放在.h或.m文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!