Objective-C – Importance of Writing Header Files

headersobjective c

Before you whip out your snarky comments, I know — this is a nooby question. This is my first time using a C based language.

I'm an undergrad student learning Objective C for a computer science course on mobile development. I know that, in an academic setting, a lot of real-world considerations aren't necessary since you're building smaller projects, work in smaller teams, etc.

But our professor demands — and XCode supports — .h header files for every .m implementation file. To me, it kind of seems like busy work. I have to make sure I copy every method signature and instance variable over to the other file. If I change one file, I have to make sure it's consistent with the other file. It seems like just a bunch of small annoyances like that.

But I know there has to be some real-world use for header files. A great answer would address both:

  1. What is a header file useful for that an implementation file isn't suited for? What is its purpose?
  2. Why do we as programmers have to manually write our header files? It seems like they could easily be generated automatically.

Thanks in advance!

Best Answer

  1. In short;

    • The header file defines the API for a module. It's a contract listing which methods a third party can call. The module can be considered a black box to third parties.

    • The implementation implements the module. It is the inside of the black box. As a developer of a module you have to write this, but as a user of a third party module you shouldn't need to know anything about the implementation. The header should contain all the information you need.

  2. Some parts of a header file could be auto generated - the method declarations. This would require you to annotate the implementation as there are likely to be private methods in the implementation which don't form part of the API and don't belong in the header.

Header files sometimes have other information in them; type definitions, constant definitions etc. These belong in the header file, and not in the implementation.

Related Topic