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.
In Objective-C, the class interface specifies exactly how a given type of object is intended to be used by other objects. In other words, it defines the public interface between instances of the class and the outside world.
Structures and classes are general-purpose, flexible constructs that become the building blocks of your program's code. You define properties and methods to add functionality to your structures and classes using the same syntax you use to define constants, variables, and functions.
You can create a class reference with the following code: Class M = [NSMutableString class]; // NSMutableString (for example). You can then call methods on that saved class with code like this: [M string];
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.
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