@class vs. #import
If you see this warning:
warning: receiver 'MyCoolClass' is a forward class and corresponding @interface may not exist
you need to
#import the file, but you can do that in your implementation file (.m), and use the
@class declaration in your header file.
@class does not (usually) remove the need to
#import files, it just moves the requirement down closer to where the information is useful.
If you say
@class MyCoolClass, the compiler knows that it may see something like:
It doesn't have to worry about anything other than
MyCoolClass is a valid class, and it should reserve room for a pointer to it (really, just a pointer). Thus, in your header,
@class suffices 90% of the time.
However, if you ever need to create or access
myObject's members, you'll need to let the compiler know what those methods are. At this point (presumably in your implementation file), you'll need to
#import "MyCoolClass.h", to tell the compiler additional information beyond just "this is a class".
Look at the Objective-C Programming Language documentation on ADC
Under the section on Defining a Class | Class Interface it describes why this is done:
The @class directive minimizes the amount of code seen by the compiler and linker, and is therefore the simplest way to give a forward declaration of a class name. Being simple, it avoids potential problems that may come with importing files that import still other files. For example, if one class declares a statically typed instance variable of another class, and their two interface files import each other, neither class may compile correctly.
I hope this helps.
Three simple rules:
#importthe super class, and adopted protocols, in header files (
#importall classes, and protocols, you send messages to in implementation (
- Forward declarations for everything else.
If you do forward declaration in the implementation files, then you probably do something wrong.