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 nameViewController
should 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.h
which does#import "b.h"
. Now every file that importsa.h
automatically also importsb.h
which 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
#import
s 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:
A forward class declaration:
Is used in header files where no specific property, attribute or method information is required.
This allows
#import
or#include
of the header file without any of the overhead that comes with#import
ing ClassName.h.#import
is using for a class that is predefined by us or by Apple xcode but @class is we using before we define it (It's forward declaration of class) , in our parent/ or previous classso it tell the compiler that there is a class with this name in our project, so that compiler dont put errors for that class name.