Objective-c头文件中class和interface的关键字 [英] The keyword of class and interface at header file in Objective-c

查看:66
本文介绍了Objective-c头文件中class和interface的关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
@class vs. #import

我是 Objective-c 的新手,我看过一个例子:

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

以上代码存放在MapKitSampleAppDelegate.h"文件中,请问第3行@class MapKitSampleViewController;"是什么意思?我们可以将其更改为 #import "MapKitSampleViewController.h" 吗?

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

推荐答案

我想问一下第3行是什么意思MapKitSampleViewController"?我们可以将其更改为#importMapKitSampleViewController.h"?

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

是的.

@class 关键字是一个前向声明".你告诉编译器是这个类将在这个类中使用,但它的头文件导入将在别处.

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

如果您查看 .m 文件,很可能会发现 #import "MapKitSampleViewController.h" 将在那里.

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

为什么?

实现这一点的原因(我认为,无论如何),是为了防止循环导入.想象一下发生以下情况的场景:

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

现在,如果我没记错的话,这里发生的情况是,在编译过程中,它会反复导入头文件,并且会发生不好的事情.@class 关键字旨在防止这种情况发生,因为这些文件的导入将发生在 .m 文件中,而不是在 .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.

顺便说一句,这是 @class vs. #import

因此,您可能会在该问题中找到有关此主题的更深入的论述.

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

这篇关于Objective-c头文件中class和interface的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆