@class 与 #import [英] @class vs. #import

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

问题描述

据我所知,在 ClassA 需要包含 ClassB 标头且 ClassB 需要包含 ClassA 标头以避免任何循环包含的情况下,应该使用前向类声明.我也明白 #import 是一个简单的 ifndef,因此包含只发生一次.

It is to my understanding that one should use a forward-class declaration in the event ClassA needs to include a ClassB header, and ClassB needs to include a ClassA header to avoid any circular inclusions. I also understand that an #import is a simple ifndef so that an include only happens once.

我的问题是:什么时候使用#import,什么时候使用@class?有时,如果我使用 @class 声明,我会看到一个常见的编译器警告,如下所示:

My inquiry is this: When does one use #import and when does one use @class? Sometimes if I use a @class declaration, I see a common compiler warning such as the following:

warning:receiver 'FooController' 是一个转发类,对应的@interface 可能不存在.

真的很想理解这一点,而不是仅仅删除 @class 前向声明并抛出一个 #import 以消除编译器给我的警告.

Would really love to understand this, versus just removing the @class forward-declaration and throwing an #import in to silence the warnings the compiler is giving me.

推荐答案

如果您看到此警告:

警告:接收者'MyCoolClass'是一个转发类,对应的@interface可能不存在

warning: receiver 'MyCoolClass' is a forward class and corresponding @interface may not exist

您需要 #import 文件,但您可以在您的实现文件 (.m) 中执行此操作,并在您的头文件中使用 @class 声明.

you need to #import the file, but you can do that in your implementation file (.m), and use the @class declaration in your header file.

@class 不会(通常)消除对 #import 文件的需要,它只是将需求向下移动到更接近信息有用的地方.

@class does not (usually) remove the need to #import files, it just moves the requirement down closer to where the information is useful.

例如

如果你说@class MyCoolClass,编译器知道它可能会看到类似:

If you say @class MyCoolClass, the compiler knows that it may see something like:

MyCoolClass *myObject;

它不必担心除了 MyCoolClass 是一个有效的类之外的任何东西,它应该为指向它的指针(实际上,只是一个指针)保留空间.因此,在您的标题中,@class 在 90% 的情况下就足够了.

It doesn't have to worry about anything other than MyCoolClass is a valid class, and it should reserve room for a pointer to it (really, just a pointer). Thus, in your header, @class suffices 90% of the time.

然而,如果您需要创建或访问 myObject 的成员,您需要让编译器知道这些方法是什么.此时(大概在您的实现文件中),您需要#import "MyCoolClass.h",告诉编译器除了这是一个类"之外的其他信息.

However, if you ever need to create or access myObject's members, you'll need to let the compiler know what those methods are. At this point (presumably in your implementation file), you'll need to #import "MyCoolClass.h", to tell the compiler additional information beyond just "this is a class".

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

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