Note: This post is part 2 of a series of posts I will do about the new book of Matt Galloway.
Minimize Importing Headers in Headers
The second item, unfortunately a short one, talks about importing classes: the where and the how. One should be careful when importing things he doesn’t need on the .h file. Most of the time, specifying
@class (forward declaration) instead of an
#import is the best choice. Importing creates dependences between classes that should be avoided (when possible). So what does this
@class actually means?
“The @class directive minimizes the amount of code seen by the compiler and linker, and is therefore the simplest way to give a forward declaration of a class name. Being simple, it avoids potential problems that may come with importing files that import still other files. For example, if one class declares a statically typed instance variable of another class, and their two interface files import each other, neither class may compile correctly.” – Abizern, http://stackoverflow.com/a/323510/491239.
So in a nutshell (from Mr. PeyloW, http://stackoverflow.com/a/1350029/491239):
#import the super class, and adopted protocols, in header files.
#import all classes, and protocols, you send messages to in implementation.
- Forward declarations for everything else.
And a quick example:
“The reasoning behind forward declarations in header files is that it avoids unnecessary dependencies. i.e. Imagine B.h forward declares A and B.m imports A.h. Then imagine C.m, D.m, E.m and F.m import B.h. After all this is done, A.h changes. Since A is only forward declared in B.h, only B.m needs to rebuild. Without forward declarations, C.m, D.m, E.m and F.m would all need to be rebuild if A changes” – Jacob Relkin, http://stackoverflow.com/a/2770246/491239
Hope you enjoyed this quick reference to how to import in objective-c.