Thursday, December 31, 2015

@class vs. #import

@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.