Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

objective-c

People also ask

Do you have to include .C file in .h file?

You are correct that you do not HAVE to include the module's header file in the module's C file. There are a few reasons why you may wish to do so. (What follows is a non-exhaustive list). As others have noted, it helps ensure that the declarations in the header file are consistent with the definitions in the C file.

What do you put in .h files?

Header files ( . h ) are designed to provide the information that will be needed in multiple files. Things like class declarations, function prototypes, and enumerations typically go in header files. In a word, "definitions".

Why do we need .h file in C?

Header files serve two purposes. System header files declare the interfaces to parts of the operating system. You include them in your program to supply the definitions and declarations you need to invoke system calls and libraries.

What is the purpose of .h files?

Header files are used in C++ so that you don't have to write the code for every single thing. It helps to reduce the complexity and number of lines of code. It also gives you the benefit of reusing the functions that are declared in header files to different .


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.


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.


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


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