根据我的理解,在ClassA需要包含ClassB标头,而ClassB需要包含ClassA标头以避免任何循环包含的情况下,应该使用前向类声明。我还理解#import是一个简单的ifndef,因此include只发生一次。

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

警告:接收端FooController是转发类,对应的@interface可能不存在。

我真的很想理解这一点,而不是仅仅删除@class forward-declaration并抛出一个#import来沉默编译器给我的警告。


当前回答

我看到很多“这样做”,但我没有看到任何“为什么”的答案。

那么:为什么在头文件中使用@class,而在实现中使用#import呢?一直使用@class和#import会使你的工作加倍。除非你使用继承。在这种情况下,您将为单个@class #import多次。然后,如果您突然决定不再需要访问某个声明,您必须记得从多个不同的文件中删除。

由于#import的性质,多次导入同一个文件不是问题。 编译性能也不是真正的问题。如果是的话,我们就不会在几乎每个头文件中都使用#importing Cocoa/Cocoa.h之类的代码了。

其他回答

如果需要,在头文件中使用前向声明,并为在实现中使用的任何类导入头文件。换句话说,您总是#import您在实现中使用的文件,如果您需要在头文件中引用一个类,也可以使用forward声明。

例外的是,你应该在头文件中导入一个类或正式协议(在这种情况下,你不需要在实现中导入它)。

查看关于ADC的Objective-C编程语言文档

在定义类|类接口一节中,它描述了为什么这样做:

@class指令最大限度地减少了编译器和链接器看到的代码量,因此是给出类名正向声明的最简单方法。由于简单,它避免了导入仍然导入其他文件的文件时可能出现的潜在问题。例如,如果一个类声明了另一个类的静态类型实例变量,并且它们的两个接口文件相互导入,那么两个类都不能正确编译。

这是一个示例场景,其中我们需要@class。

考虑一下,如果您希望在头文件中创建一个协议,该协议的参数具有相同类的数据类型,那么您可以使用@class。请记住,您也可以单独声明协议,这只是一个示例。

// DroneSearchField.h

#import <UIKit/UIKit.h>
@class DroneSearchField;
@protocol DroneSearchFieldDelegate<UITextFieldDelegate>
@optional
- (void)DroneTextFieldButtonClicked:(DroneSearchField *)textField;
@end
@interface DroneSearchField : UITextField
@end

有关文件依赖关系& #import & @class的更多信息,请查看以下内容:

http://qualitycoding.org/file-dependencies/ 这是篇好文章

文章摘要

imports in header files: #import the superclass you’re inheriting, and the protocols you’re implementing. Forward-declare everything else (unless it comes from a framework with a master header). Try to eliminate all other #imports. Declare protocols in their own headers to reduce dependencies. Too many forward declarations? You have a Large Class. imports in implementation files: Eliminate cruft #imports that aren’t used. If a method delegates to another object and returns what it gets back, try to forward-declare that object instead of #importing it. If including a module forces you to include level after level of successive dependencies, you may have a set of classes that wants to become a library. Build it as a separate library with a master header, so everything can be brought in as a single prebuilt chunk. Too many #imports? You have a Large Class.

如果我们这么做

@interface Class_B : Class_A

意味着我们将Class_A继承到Class_B,在Class_B中我们可以访问Class_A的所有变量。

如果我们这样做

#import ....
@class Class_A
@interface Class_B

这里我们说我们在程序中使用Class_A,但如果我们想在Class_B中使用Class_A变量,我们必须在.m文件中#import Class_A(创建一个对象并使用它的函数和变量)。