Possible Duplicate:
@class vs. #import
In the .h file you can add a class to be seen(dont know what the correct terminolgy for this is) by using
#import "SomeClass.h"
or instead use
@class SomeClass;
I’ve tried both methods and they both worked. Whats the difference? Should I be using one of the methods and not the other? What is best practice?
#importincludes the content of the header in the source.Thus, every declaration which is in the imported header is also imported.
@classonly declares to the compiler that the given class exists, but does not import the header itself. It is called a forward declaration, as you only declares to the compiler that the class exists before defining it in details (telling which methods it implements and so on)Consequences:
#importin your.mfile, if the header is modified, it will trigger the recompilation of the.mfile that#importit on next compilation. Instead, if you use@class, your.mdoes not depend on the header and if the header is modified, the.mfile is not recompiled.@classalso avoid cross-imports, e.g. if the class A references class B and class B references class A, then you can’t#import "A.h"in B.h and#import B.hin A.h in the same time (it would be an “import infinite loop”)@classonly declare that a class exists and does not tell the compiler which methods the class responds to.This is why usually the best practice is to forward-declare the class using
@class Ain the header (.h) files that references class A, just so that the compiler knows that “A” is a known class but doesn’t need to know more, and#import "A.h"in the implementation (.m) file so that you can call methods on the objet of class A in your source file.In addition to avoid import loops, this will also avoid to recompile files if they don’t need to, and thus reduce your compile time.
The only exceptions are when the declaration of your class inherits another class, or when it declares that it conforms to a given
@protocol(like delegate protocols and so on), because in this particular case, the compiler needs you to#importthe whole definition of the parent class or@protocol(to know if your class correctly conforms to this given protocol).MyClassA.h
MyClassB.h
MyClassA.m
MyClassB.m
PS: Note that if this is a best practice, I know a lot of developers (including myself sometimes ^^) that
#importthe header it needs in their .h files, instead of only forward-declare it using@class… this is some bad habit — or because these developers doesn’t know these subtleties — that you will unfortunately encounter in existing code anyway.