开发者

Should header files be included in .h or .m files?

If I have four .h/.m file pairs

file1.h

file2.h

file3.h

file4.h

where I am using file1.h, file2.h, and file3.h functionality in file4, should those header files be included in file4.h or开发者_JS百科 file4.m?


In the .m file if possible. You may have to forward declare classes in the .h file, like:

@class AClassIImportInDotMFile;

If Class B is a subclass of Class A, you need to import Class A's .h file in Class B's .h file.


I assume file4.h is going to be used by other .m files. If so, only include in file4.h what is used in file4.h, and the rest in file4.cpp. This will reduce the overal number of inclusions and including file4.h will not pull useless additional headers.

When the number of required .h files starts to grow inconveniently, you can group them in topic headers. For instance, topic1.h may include file1.h and file2.h but not file3.h.


I Usually import the other headers into the current header file if I plan on using their classes in property declaration. However this can create some havoc if the classes reference each other.

If this is the case then you will want to include the headers in the .m file so they can be used inside the class, but for any external access to these items you would use id in the place of your custom classes. And cast them when you get them in the other referencing methods.

I run into this issue if I include the AppDelegate.h and then reference the other class in app delegate.
the reason for this would be that I want to include a reference to my current object in the app delegate, but the class also uses the app delegate to access other classes. In this case I would include the Classes in the AppDelegate.h and include AppDelegate.h in the m file of the class.

I hope that made sense.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜