IPhone SDK: what's the difference between #import and @class?

We can import the class declaration using #import:

#import "SomeClass.h" 

or declare using @class:

 @class SomeClass; 

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

+6
iphone
source share
1 answer

"Import" binds the header file that it contains. Everything in the header, including property definitions, method declarations, and any import data in the header, becomes available. Import provides actual linker definitions.

@class, by contrast, simply tells the linker not to complain that it has no definition for the class. This is the โ€œcontractโ€ that you will give the definition for the class at another point.

Most often you use @class to prevent circular imports, that is, ClassA refers to ClassB, so it imports ClassB.h into its own ClassA.h, but ClassB also refers to ClassA, so it imports ClassA.h into ClassB.h. Since the import statement imports the header 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 will not recognize ClassB when it appears in ClassA.h. @class ClassB; directive @class ClassB; tells the linker that you will provide a header for ClassB later before it is actually used in the code.

+11
source share

All Articles