最佳实践和理由:#import in .m 或 .h [英] Best practice and rationale: #import in .m or .h

查看:45
本文介绍了最佳实践和理由:#import in .m 或 .h的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Objective-C 中将#import 语句放置在 .m 而不是 .h 文件中的基本原理是什么?

What's the rationale behind placing #import statements in .m rather than .h files in Objective-C?

Apple 示例将它们捆绑在 .m 文件中,除非在接口声明 (.h) 中使用了对象,并且文档声明这是正确的(在接口文件中,您首先导入任何必需的头文件.")

Apple examples bundle them in .m file unless object is used in interface declaration (.h), and docs state that this is correct ("In the interface file, you first import any required header files.")

让我困惑的是 .h 应该定义实现的接口,所以 #import 逻辑上会转到 .h 文件而不是 .m.

What's confusing me is that .h is supposed to define the interface for the implementation, so #import would logically go to .h file instead of .m.

推荐答案

在任何源文件中,您应该只#import 使该文件对编译有效所需的内容.请记住,您的标头可能会被其他类使用,因此您希望使它们尽可能轻巧.这也是为什么最好将@class 用于超类以外的类的前向声明.

In any source file, you should only #import what you need to make that file valid for compilation. Keep in mind that your headers might be used by other classes, so you want to make them as lightweight as possible. This is also why it's preferable to use @class for forward declarations of classes other than your superclass.

这篇关于最佳实践和理由:#import in .m 或 .h的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆