开发者

Downside to including headers in every source file (Objective-C)

I'm currently including my AppDelegate.h and all of my category headers into every one of my source files using the MyApp_Prefix.pch prefix header, instead of manually #importing them only where they are used. The category methods and lots of compiler #define's in my app delegate are used in lots of places in my code.

Is there any down side to this开发者_C百科? Is it just that compilation will take longer?


Source level dependencies. By effectively importing the headers into every source file it means that every source file potentially depends on it, but the dependency is not visible. Source level dependencies are insidious. They can creep up when you're not looking and then it's hard to disentangle them. They can introduce other nasties such as include file ordering issues.

OTOH for small projects this may not be a huge issue a lot of the time.

Nonetheless for me personally I am in the habit of never depending on another source file unnecessarily - which means my header files rarely #import other (non-framework) headers. In Objective-C you can usually do this more cleanly than, say, C++, because you always hold Objective-C objects by pointer so they only need a forward declaration in the header.


Is there any down side to this? Is it just that compilation will take longer?

No, not really. It does mean that every time you make a change to any header, the whole project gets recompiled. But on the other hand, because it is precompiled there might be a saving in the case where you need to recompile but don't change your headers.

There's an advantage to stuffing all your headers in the pch file because it means you are less likely to omit a header by accident. Sometimes Objective-C compiles things wrongly if it doesn't have a header file e.g. if you have two classes with a methods declared like:

-(void) doSomethingWith: (float) aNumber;

and

-(void) doSomethingWith: (double) aNumber;

without the correct headers, Objective-C might guess the wrong doSomethingWith: and pass a double where a float is expected or vice versa.

Having said all that, I never bother with the pch. I tend to only import headers in .m files where possible and forward declare classes in header files.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜