LeeMobile
LeeMobile

Reputation: 3825

Objective-C: Importing headers in .h or .m?

I'm new to objective-c and would like to know the best practice for importing some external headers that I use in my class.

Should I be storing the #import "classB.h" in my own classes .h file or in the .m file?

What's the difference?

Thanks!

Upvotes: 27

Views: 13475

Answers (4)

Constantino Tsarouhas
Constantino Tsarouhas

Reputation: 6886

It's recommended that you import other header files in your header file. That way you can use the class in both the header and the implementation files (because the implementation file (.m) imports its associated header file).

If you want to know when to import files and when to use forward-class declaration, you can go here. ;-)

Upvotes: 2

user100531
user100531

Reputation:

It is proper practice to put a forward class declaration (@class classB;) in the header and #import "classB.h in the .m

A forward class declaration, like @class classB; lets the compiler know it should expect the class later on, and it shouldn't complain about it at the moment.

Upvotes: 37

Marc Charbonneau
Marc Charbonneau

Reputation: 40513

To avoid circular references, only #import a header file in another class's header file if it's inheriting from that class. Otherwise, use @class ClassName to declare the class type if you need it in your header file, and #import it in the implementation file.

Upvotes: 11

Marc W
Marc W

Reputation: 19251

To the compiler, it really doesn't matter. You could just throw forward declarations in your .h and then wait to #import until your .m file. See this post on SO for more info on this.

From a clean-code prospective, some may argue that putting the imports in your implementation file keeps the details closer to where they are needed (see that link above as well; the people there reference this idea).

Upvotes: 4

Related Questions