Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing header in objective c

In Objective-c when we using object of one class into another class by convention we should forward declare the class in .h file, i.e. @class classname;. And should import the header file in .m file, i.e. #import "header.h". But if we import the header file in .h then we don't have to import it again in .m file . So what is the reason behind this convention? Which is efficient way?

like image 256
V-Xtreme Avatar asked May 10 '12 10:05

V-Xtreme


2 Answers

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.

like image 62
justin Avatar answered Sep 19 '22 17:09

justin


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

like image 22
Attila Avatar answered Sep 21 '22 17:09

Attila