Importing header in objective c
So what is the reason behind this convention?
You should favor forward declarations (@class MONClass;
) where possible because the compiler needs to know a typename is an objc class before it is used, and because an #import
can drag in a ton of other headers (e.g. entire frameworks/libraries), seriously expanding and complicating your dependencies and increasing your build times.
Which is efficient way?
Forward declarations. Your builds, rebuilds, and indexing will be much faster if you do this correctly.
You are correct that importing the header in the .h makes like easier (in the short run). The reason not to do this and import it in the implementation file (.m) is to prevent name pollution, where all the names in the imported header are available when someone imports your header. Instead, by importing your header only your functions/classes shuld be imported and the rest at the implementation
Also, if you import the header in the .h, that means every code that imported your header will have to be recompiled when the 3rd-party header changes, even if nothing has changed in your header explicitly. Forward declaration avoids this problem and forces only those implementation (.m) files to be recompiled that actually make use of the 3rd-party header
Though import of files in .m makes it easier to get away with few lines of code but it is general thinking that importing may affect the load time and response time , yes it does affect and does not.Because according to documentation by apple :-
If you are worried that including a master header file may cause your program to bloat, don’t worry. Because Mac OS X interfaces are implemented using frameworks, the code for those interfaces resides in a dynamic shared library and not in your executable. In addition, only the code used by your program is ever loaded into memory at runtime, so your in-memory footprint similarly stays small.
As for including a large number of header files during compilation, once again, don’t worry. Xcode provides a precompiled header facility to speed up compile times. By compiling all the framework headers at once, there is no need to recompile the headers unless you add a new framework. In the meantime, you can use any interface from the included frameworks with little or no performance penalty.
Thus Response and load times are affected for the first time only , But anyways forward referencing should be favoured to maintain coding standards and avoid overheads however small :).