difference between #import and @class in my simple case
In my controller's header file, I need to declare a instance of another controller. I did it in the following way:
#import "BIDMyRootController.h" #import "BIDAnotherController.h" //I import another controller's header @interface BIDCurrentController : BIDMyRootController //I declare an instance of another controller @property (strong, nonatomic) BIDAnotherController *anotherController; @end
The above code is pretty straight forward. No problem!
But I also noticed that, alternatively, I can use @class to replace my #import statement for BIDAnotherController in the following way:
#import "BIDMyRootController.h" @class BIDAnotherController //I declare another controller with @class tag @interface BIDCurrentController : BIDMyRootController //I declare an instance of another controller @property (strong, nonatomic) BIDAnotherController *anotherController; @end
No problem too!
But I am confused now, what are the differences between #import "BIDAnotherController.h" and @class BIDAnotherController then if they are both ok???
By the way, in the implementation file of BIDCurrentController, I have imported BIDAnotherController again:
#import "BIDCurrentController.h" #import "BIDAnotherController.h" //import another controller again @implementation BIDCurrentController ... @end
Using @class BIDAnotherController is called a forward declaration of BIDAnotherController, which basically tells the compiler that an implementation for it will exist at some point in the future.
#import "BIDAnotherController.h" actually includes the contents of BIDAnotherController.h into the current file.
If you only need to use BIDAnotherController as a property or argument to a method, you can get away with the forward declaration because your code doesn't need to know anything about it other than it exists. If instead you need to use properties or methods of BIDAnotherController then you'll need to import its header (otherwise the compiler won't know those properties or methods even exist!).
Typically forward declarations are used to break an include cycle between two or more header files. The easiest way to prevent a cycle is to prefer @class declarations unless you really do need access to properties or methods of a class.