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

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

问题描述

据我的理解,在事件ClassA需要包括一个ClassB头,而ClassB需要包括一个ClassA头以避免任何圆形包含的事件中使用一个forward类声明。我也明白, #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:


警告: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 c>,编译器知道它可能会看到像:

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 的成员,您需要让编译器知道这些方法是什么。在这一点上(可能在你的实现文件中),你需要 #importMyCoolClass.h,告诉编译器除了this is a class 。

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 vs. #import的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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