您是否将#import放在.h或.m文件中? [英] Do you put #import s in .h or .m files?

查看:83
本文介绍了您是否将#import放在.h或.m文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道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 #importing 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆