【问题标题】:difference between #import and @class in my simple case在我的简单案例中,#import 和 @class 之间的区别
【发布时间】:2013-05-01 14:48:57
【问题描述】:

在我的控制器的头文件中,我需要声明另一个控制器的实例。我是通过以下方式做到的:

#import "BIDMyRootController.h"
#import "BIDAnotherController.h" //I import another controller's header

@interface BIDCurrentController : BIDMyRootController

//I declare an instance of another controller
@property (strong, nonatomic) BIDAnotherController *anotherController;

@end

上面的代码非常简单。没问题!

但我也注意到,或者,我可以使用 @class 以下列方式替换我的 #import 语句为 BIDAnotherController

#import "BIDMyRootController.h"
@class BIDAnotherController //I declare another controller with @class tag

@interface BIDCurrentController : BIDMyRootController

//I declare an instance of another controller
@property (strong, nonatomic) BIDAnotherController *anotherController;

@end

也没问题!

但我现在很困惑,#import "BIDAnotherController.h"@class BIDAnotherController 有什么区别那么如果它们都ok???


更新:

对了,在BIDCurrentController的实现文件中,我又导入了BIDAnotherController

#import "BIDCurrentController.h"
#import "BIDAnotherController.h" //import another controller again
@implementation BIDCurrentController
...
@end

【问题讨论】:

  • @class vs. #import 的可能重复项我添加了我的答案,但又想起了这个问题..
  • @class 将类名声明为编译器的类型,因此您可以定义指向该类实例的指针。没有声明类的方法、属性或实例变量,因此您不能在任何地方“使用”该类型的对象,只能传递它们的指针。

标签: ios objective-c uiviewcontroller forward-declaration


【解决方案1】:
  • 使用@class BIDAnotherController 被称为BIDAnotherController 的前向声明,它基本上告诉编译器它的实现将在将来的某个时候存在。

  • #import "BIDAnotherController.h"实际上将BIDAnotherController.h的内容包含到当前文件中。

如果您只需要将BIDAnotherController 用作方法的属性或参数,则可以避免使用前向声明,因为您的代码除了它存在之外不需要知道任何关于它的信息。如果您需要使用 BIDAnotherController 的属性或方法,则需要导入其标头(否则编译器甚至不会知道这些属性或方法存在!)。

通常使用前向声明来中断两个或多个头文件之间的包含循环。防止循环的最简单方法是首选@class 声明,除非您确实需要访问类的属性或方法。

【讨论】:

  • 这一切都很好。我只是最好的做法是尽可能使用前向声明,以使您的代码尽可能模块化和封装。 #imports 在更大的项目中很容易失控。在不知不觉中,您有不必要的导入、导入周期和疯狂的意大利面条依赖。如果一个类只需要知道另一个类的存在,而不是调用它的任何方法或设置它的任何属性,请使用@class。
  • 谢谢大家,我现在很清楚,我会在 2 分钟内接受这个答案
猜你喜欢
  • 2013-10-28
  • 1970-01-01
  • 2015-11-11
  • 2017-06-30
  • 2012-01-13
  • 1970-01-01
  • 1970-01-01
  • 2021-05-28
  • 1970-01-01
相关资源
最近更新 更多