tags:

views:

196

answers:

6

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.

+1  A: 

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

Perhaps in one of the methods in the implementation, you have instantiated a local variable of a class type that you might only use once or twice, and you do not want to have the #import statement clutter your header file. Or you might have used @class in the header as a forward declaration, and you need to reference that class in your implementation with the #import statement.

Alex Reynolds
+8  A: 

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.

Chuck
+1  A: 

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.

Donnie C
+5  A: 

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.

NSResponder
+3  A: 

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).

dreamlax
+1  A: 

Everything else aside, it's also a performance win for compile times. When you #import a file, it's as if you pasted the contents of the file into your header. That's more stuff for the compiler to get through when compiling your code.

See this page about Clang compiler performance.

Note that precompiled headers alleviate much of the problem in the case of standard headers like Cocoa.h.

Ken