tags:

views:

92

answers:

1

We can import class declaration with #import:

#import "SomeClass.h"

or declare with @class:

@class SomeClass;

What's the difference and when we should use each of them?

+4  A: 

"Import" links the header file it contains. Everything in the header, including property definitions, method declarations and any imports in the header are made available. Import provides the actual definitions to the linker.

@class by contrast just tells the linker not to complain it has no definition for a class. It is a "contract" that you will provide a definition for the class at another point.

Most often you use @class to prevent a circular import i.e. ClassA refers to ClassB so it imports ClassB.h in its own ClassA.h but ClassB also refers to ClassA so it imports ClassA.h in ClassB.h. Since the import statement imports the imports of a header, this causes the linker to enter an infinite loop.

Moving the import to the implementation file (ClassA.m) prevents this but then the linker won't recognize ClassB when it occurs in ClassA.h. The @class ClassB; directive tells the linker that you will provide the header for ClassB later before it is actually used in code.

TechZen
Very good explanation. Thanks!
sashaeve