I have a basic best-practices question in Objective C. I understand the difference between @class and #import but I do not understand why the default Apple Xcode templates do this:
AppDelegate.h:
@class ViewController;
.m:
#import "ViewController.h
When you could instead just put the latter #import in the .h and leave mention of ViewController out of the .m altogether, thereby simplifying by 1 line of code.
Of course, saving 1 line of code is not the issue, I’m just curious why it’s being done this way?
The line
@class ViewController;is a forward declaration so the compiler has an idea what the nameViewControllershould mean. The point is to try to do as few#import‘s in a header file as possible to speed up compiling.Imagine a file
a.hwhich does#import "b.h". Now every file that importsa.hautomatically also importsb.hwhich increases the amount of work the compiler has to do. By using forward declarations one can often avoid such additional imports and thus avoid the additional work for the compiler.The bigger the project and the more complex the class hierarchies and dependencies become the more these
#imports can become an issue. So it’s a good idea to develop a habit of using forward declarations where possible.Edit: After the comments, another important use-case surfaced: to resolve cyclic dependencies. For example, if class A wants to reference class B and vice versa, one has to be defined before the other. But because they need to know the other we have a paradox. It’s solved like this: