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?
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With