OGeek|极客世界-中国程序员成长平台

标题: ios - 在我的简单案例中,#import 和 @class 之间的区别 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 02:32
标题: ios - 在我的简单案例中,#import 和 @class 之间的区别

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

#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 以下列方式替换 BIDAnotherController#import 语句:

#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??? p>


更新:

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

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



Best Answer-推荐答案


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

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

关于ios - 在我的简单案例中,#import 和 @class 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16320407/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4