• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 在我的简单案例中,#import 和 @class 之间的区别

[复制链接]
菜鸟教程小白 发表于 2022-12-13 02:32:22 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

在我的 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-推荐答案


  • 使用 @class BIDAnotherController 被称为 BIDAnotherController 的前向声明,它基本上告诉编译器它的实现将在未来的某个时候存在.

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

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

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

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

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap