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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
“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.