@class和#import有什么区别 [英] What is the difference between @class and #import

查看:103
本文介绍了@class和#import有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用以下代码进行编译时,没有错误:

When I compile with the following code there are no errors:

@class RootViewController;
//#import "RootViewController.h"

使用以下代码进行编译时,出现错误:

When I compile with the following code I get an error:

//@class RootViewController;
#import "RootViewController.h"

错误:'RootViewController'之前的预期说明符-限定符列表"

"error: expected specifier-qualifier-list before 'RootViewController'"

我不明白两者之间的区别,因为我在类似的类中使用了#import,并且编译时没有错误!

I don't understand what the difference is between the two because I used #import in a similar class and it compiled without errors!

推荐答案

由于我仍然感到困惑,我决定参考该文档:

I decided to refer to the documentation because I was still confused:

#import

此伪指令与#include相同,不同之处在于它确保不会重复包含同一文件.因此,它是首选,并且在整个基于Objective-C的文档中的代码示例中代替#include来使用.

This directive is identical to #include, except that it makes sure that the same file is never included more than once. It’s therefore preferred and is used in place of #include in code examples throughout Objective-C–based documentation.

此约定意味着每个接口文件都间接包括所有继承类的接口文件.当源模块导入类接口时,它会获取该类所基于的整个继承层次结构的接口.

This convention means that every interface file includes, indirectly, the interface files for all inherited classes. When a source module imports a class interface, it gets interfaces for the entire inheritance hierarchy that the class is built upon.

@class

这样的声明只是使用类名作为类型,而不依赖于类接口的任何细节(其方法和实例变量),@ class指令为编译器充分警告了所期望的内容.但是,在实际使用类接口的地方(创建实例,发送消息),必须导入类接口.

Declarations like this simply use the class name as a type and don’t depend on any details of the class interface (its methods and instance variables), the @class directive gives the compiler sufficient forewarning of what to expect. However, where the interface to a class is actually used (instances created, messages sent), the class interface must be imported.

http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocDefiningClasses.html#//apple_ref/doc/uid/TP30001163-CH12-TPXREF123

这篇关于@class和#import有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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