为什么 Objective-C 使用头文件而不是像 Java 那样使用单文件类?
我主要使用 Java 工作,最近正在尝试学习 Objective-C 来进行 Mac 和 iOS 应用程序开发。现在,这种语言与我习惯的指针、消息等有很大不同,但我似乎还可以接受它。这并不是一个编码问题,但我宁愿正确地熟悉我正在处理的事情,而不是仅仅知道“它必须是这样的,因为它就是这样的”。
为什么 Objective-C 语言需要头文件?它们与 .m 文件分离的实际目的是什么?为什么函数需要在标头中声明而不是仅仅实现?它只是一种尚未从旧语言中消亡的事物之一,还是相对于 Java 的单文件类有真正的优势?
I primarily work in Java and am recently trying to learn Objective-C for Mac and iOS app development. Now, this language is quite different from what I'm used to, pointers, messages, etc, but I seem to be picking it up okay. This isn't a coding problem per say but I'd rather be properly familiar with what I'm dealing with rather than just knowing "it has to be that way just because that's how it is".
Why does the Objective-C language need header files? What is their actual purpose for being separate from the .m file? Why do functions need to be declared in the header as opposed to just implemented? Is it just one of those things that just haven't died out from an old language, or is there a real advantage as opposed to Java's one-file classes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
.h 文件的存在主要是因为 C 的向下兼容性 - 所有 C 代码也是有效的 Objective-C 代码。 AC 编译器一次只处理一个文件;每个文件都是独立编译和解析的。 C 编译器“必须”在第一次使用之前看到某个符号的声明。因此,如果您在 Bm 中使用类 A,则编译器在某些时候一定已经看到了 A 的声明;为了避免像
#include "Am"
那样的事情,约定是拆分头文件中的声明和 .c、.m、.cpp... 文件中的实现。其他语言如Java在编译时会自动扫描B.java同目录下的文件,查找其他类的声明; C 编译器有点“旧”,需要您 #include 所有必要的头文件。
简而言之:主要是历史原因。
Mainly .h files exist because of downward compatibility of C - all C code is also valid Objective-C code. A C compiler works one file at a time; each file is compiled and parsed independently. The C compiler "must" have seen the declaration of a certain symbol before its first use. So, if you are using class A in B.m, at some point the compiler must have seen a declaration of A; to avoid doing things like
#include "A.m"
the convention is to split declarations in header files and implementation in .c, .m, .cpp... files.Other languages such as Java will automatically scan the files in the same directory of B.java when compiling it to find the declaration of other classes; C compilers are a bit "older" and need you to #include all the necessary headers.
In short: mainly historical reasons.
您不必有头文件。您可以将接口和实现放在同一个文件中,但更容易将它们分开,也使导入类更加整洁,这意味着其他类不会从 .m 继承大量不需要的内容(例如常量) )。
You don't have to have header files. You can have your interface and implementation in the same file, but it's easier to separate them, also makes importing classes neater, and it means other classes don't inherit a load of stuff they don't need from the .m (like constants).
头文件上的 Wikipedia 条目 使用与 Java 相同的比较,这是一个额外的好处:
The Wikipedia entry on header files uses the same comparison with Java that you do, which is a bonus: