3

Possible Duplicate:
@class vs. #import

I am new to Objective-c, I have seen an example look likes:

#import <UIKit/UIKit.h>

@class MapKitSampleViewController;

@interface MapKitSampleAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    MapKitSampleViewController *viewController;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;

@property (nonatomic, retain) IBOutlet MapKitSampleViewController *viewController;

@end

The above code is stored at "MapKitSampleAppDelegate.h" file, I want to ask what is the meaning of line 3 "@class MapKitSampleViewController;"? Can we change it to #import "MapKitSampleViewController.h"?

Community
  • 1
  • 1
Charles Yeung
  • 38,347
  • 30
  • 90
  • 130

2 Answers2

7

I want to ask what is the meaning of line 3 "MapKitSampleViewController"? Can we change it to #import "MapKitSampleViewController.h"?

Yes.

@class keyword is a "forward declaration". What you are telling the compiler is that this class is going to be used in this class, but the header import for it will be elsewhere.

Most likely if you look in the .m file, you will find that the #import "MapKitSampleViewController.h" will be there.

Why?

The reason why this was implemented (I think, anyway), is to prevent circular imports. Imagine a scenario where the following happens:

Class1.h

#import Class2.h

Class2.h

#import Class1.h

Now, if I'm not wrong, what happens here is that during compilation, it will repeatedly import both header and bad things happen. The @class keyword is meant to prevent this from happening, because the import for those files will happen in the .m files, not in the .h files.

BTW this is a duplicate of @class vs. #import

So you will likely find more in-depth discourse on this topic at that question.

Community
  • 1
  • 1
Daryl Teo
  • 5,394
  • 1
  • 31
  • 37
  • +1 one could also note that this works as in C++ with forward declaration vs #include. – jv42 Sep 22 '11 at 08:57
  • Yes, the #import "MapKitSampleViewController.h" is in the .m file. So, is it necessary to write the @class XXX in the .h file? – Charles Yeung Sep 22 '11 at 09:00
  • @Charles Yeung Its not necessary (as in, it will compile just fine), but it is recommended as good practice to prevent the problem I described. – Daryl Teo Sep 22 '11 at 09:01
0

Yes you can change it but this will increase the compilation time and will bring you no benefits.

The "@class MapKitSampleViewController;" is a forward declaration see http://en.wikipedia.org/wiki/Forward_declaration When using forward declaration you have to take care that you can use the forward declared class name only for type references.

alinoz
  • 2,822
  • 22
  • 38