开发者

The keyword of class and interface at header file in Objective-c [duplicate]

This question already has answers here: Closed 11 years ago.

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"?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜