i recently watched a tutorial where the speaker said that it makes no difference if you use:
#import "Class.h"
or:
@class Class;
And i have to say, my apps work the one way or the other. But there have to be a difference right? So thought i ask you guys.
Thanks in advance!
"#import" brings the entire header file in question into the current file; any files that THAT file #imports are also included.
@class, on the other hand (when used on a line by itself with some class names), just tells the compiler "Hey, you're going to see a new token soon; it's a class, so treat it that way).
This is very useful when you've got the potential for 'circular includes'; ie, Object1.h makes reference to Object2, and Object2.h makes reference to Object1. If you #import both
files into the other, the compiler can get confused as it tries to #import
Object1.h, looks in it and sees Object2.h; it tries to #import
Object2.h, and sees Object1.h, etc.
If, on the other hand, each of those files has @class
Object1; or @class
Object2;, then there's no circular reference. Just be sure to actually #import
the required headers into your implementation (.m) files.
For Example
If you say @class myClass
, the compiler knows that it may see something like:
myClass *myObject;
It doesn't have to worry about anything other than myClass 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 "myClass.h"
, to tell the compiler additional information beyond just "this is a class".
As per Apple documentation :
@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.
Great answer from here
for example when you creat a protocol:
@class yourCustomView;
@protocol yourCustomViewDelegate <NSObject>
@required
- (void) somethingDidInView:(UIView*)view;
@end
@interface yourCustomView : FIView
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With