Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice and rationale: #import in .m or .h

Tags:

objective-c

What's the rationale behind placing #import statements in .m rather than .h files in Objective-C?

Apple examples bundle them in .m file unless object is used in interface declaration (.h), and docs state that this is correct ("In the interface file, you first import any required header files.")

What's confusing me is that .h is supposed to define the interface for the implementation, so #import would logically go to .h file instead of .m.

like image 824
Rudi Avatar asked Sep 15 '09 22:09

Rudi


4 Answers

If you put all your #imports in the header files, then no two classes can mutually depend on each other, because a file can't import a file that imports it. If you put the #import in the implementation file, on the other hand, the problem goes away.

like image 117
Chuck Avatar answered Sep 29 '22 15:09

Chuck


In any source file, you should only #import what you need to make that file valid for compilation. Keep in mind that your headers might be used by other classes, so you want to make them as lightweight as possible. This is also why it's preferable to use @class for forward declarations of classes other than your superclass.

like image 45
NSResponder Avatar answered Sep 29 '22 15:09

NSResponder


If the interface of your class depends on the interface of another class (i.e. if it is a subclass) then include the header, otherwise forwardly-declare the other class with @class and include that class's interface header in dependent class's source file.

The reasoning is simple; by only referencing classes in the header rather than importing the whole interface, you can define mutually dependent classes (i.e. classes that depend on each other), otherwise such a set-up is impossible because recursive file inclusion would occur (but the Objective-C #import makes sure that doesn't happen).

like image 40
dreamlax Avatar answered Sep 29 '22 17:09

dreamlax


An interface is typically just the methods that the class makes available. One interface can have any number of interchangeable implementations. Importing inside the implementation rather than inside the header prevents other implementations from importing classes it may not need to use. It's about information hiding and keeping code on a need to know basis.

like image 32
Donnie C Avatar answered Sep 29 '22 16:09

Donnie C