Reputation: 183
Is there any difference in doing
@class MyViewController;
rather than doing the normal import of the .h into the appdelegate.h
#import "MyViewController.h"
I've seen some example recently that use the @class way and wondered if there any differences.
thanks.
Upvotes: 18
Views: 7507
Reputation: 25665
There is a big difference.
@class MyViewController;
Is a forward declaration for the object MyViewController
. It is used when you just need to tell the compiler about an object type but have no need to include the header file.
If however you need to create an object of this type and invoke methods on it, you will need to:
#import "MyViewController.h"
But normally this is done in the .m
file.
An additional use of forward declarations is when you define a @protocol
in the same header file as an object that uses it.
@protocol MyProtocolDelegate; //forward declaration
@interface MyObject {
id<MyProtocolDelegate> delegate;
...
}
...
@end
@protocol MyProtocolDelegate
... //protocol definition
@end
In the above example the compiler needs to know that the @protocol MyProtocolDelegate
is valid before it can compile the MyObject
object.
Simply moving the protocol definition above MyObject
definition would also work.
Upvotes: 21
Reputation: 47709
@class
allows you to declare that a symbol is an Objective-c class name without the need to #import the header file that defines the class.
You would use this where you only need the class name defined for the purposes of declaring a pointer to the class or a method parameter of the class, and you do not need to access any methods, fields, or properties in the class.
It saves a minuscule amount of compile time vs the #import, and it sometimes helps avoid messy include circularity issues.
[And, as rjstelling points out, it's sometimes useful where you have interleaved declarations and you need to "forward declare" something.]
Upvotes: 6