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.
If you put all your #import
s 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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With