2013-05-01 67 views
2

在我的控制器的头文件中,我需要声明另一个控制器的实例。我是这样做的:#import和@class在我的简单情况下的区别

#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 
+0

[@class vs. #import]可能的重复(http://stackoverflow.com/questions/322597/class-vs-import)我添加了我的答案,但回想起这个问题.. – 2013-05-01 14:53:38

+0

@class声明类名称作为编译器的类型,因此您可以定义指向该类实例的指针。没有声明该类的方法,属性或实例变量,因此不能在任何地方“使用”该类型的对象,只传递其指针。 – 2013-05-01 15:55:44

回答

4
  • 使用@class BIDAnotherController被称为正向声明BIDAnotherController,它基本上告诉编译器它的一个实现w在将来的某个时刻存在病态。

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

如果您只需要使用BIDAnotherController作为属性或参数的方法,你可以逃脱向前声明,因为你的代码并不需要知道这件事除了它的存在。如果您需要使用BIDAnotherController的属性或方法,那么您需要导入其头文件(否则编译器将不知道这些属性或方法甚至存在!)。

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

+1

这很好。我只是想说,尽可能使用前向声明是最好的实践,以便尽可能使代码保持模块化和封装。对于#imports来说,在一个更大的项目中非常容易失控。在你知道它之前,你有不必要的进口,进口周期和疯狂的意大利面条依赖关系。如果一个类只需要知道另一个类的存在,但不调用它的任何方法或设置它的任何属性,请使用@class。 – 2013-05-01 14:59:50

+0

我已经在添加它:) – jszumski 2013-05-01 15:00:43

+0

谢谢,现在很清楚,我会在2分钟内接受这个答案 – Mellon 2013-05-01 15:00:51

相关问题