It is to my understanding that one should use a forward-class declaration in the event ClassA needs to include a ClassB header, and ClassB needs to include a ClassA header to avoid any circular inclusions. I also understand that an #import
is a simple ifndef
so that an include only happens once.
My inquiry is this: When does one use #import
and when does one use @class
? Sometimes if I use a @class
declaration, I see a common compiler warning such as the following:
warning: receiver 'FooController' is a forward class and corresponding @interface may not exist.
Would really love to understand this, versus just removing the @class
forward-declaration and throwing an #import
in to silence the warnings the compiler is giving me.
This is an example scenario, where we need @class.
Consider if you wish to create a protocol within header file, which has a parameter with data type of the same class, then you can use @class. Please do remember that you can also declare protocols separately, this is just an example.
for extra info about file dependencies & #import & @class check this out:
http://qualitycoding.org/file-dependencies/ itis good article
summary of the article
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:
I hope this helps.
If you see this warning:
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.For Example
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".