Classes are a very important part of object oriented programming. A class is the blueprint for any object in an object-oriented programming language. It encapsulates variables and methods related to an object, and a program creates instances of objects to work with. We can discuss specifics about classes in a later post, but for now, I wanted to talk a little about header files. Classes in Objective-C are comprised of 2 files, the implementation file, and a header file. What is a header file you may ask? Keep reading and you will learn, and even if you do know, there might be some useful history you may not know.
Objective-C Classes: A Tale of Two Files
This goes all the way back to C. Back in C, if you wanted to call a method form somewhere, its signature had to be written somewhere higher in the text of the file. By somewhere higher, I literally mean an earlier line number, like if you wanted to call a method from line 20 of the file, something that denoted its signature had to be in lines 1-19. There were a few ways to do this.
You basically had 3 ways to deal with this, and 2 of them are essentially the same.
- You could just simply write the whole method above where it is called. This could have some annoying consequences of just always having to make sure you had these in some sort of usage order, and it would not make it easy to separate things into functional areas in the same code file.
- You could write something called a “prototype” near the top of the file.
- You could write the prototype in a header file, and #include it in your main code file.
A prototype is basically the first line of a method, written almost like a function call, for example:
void anAwesomeMethod(int aNumber, int anotherNumber);
In my research for this article, I learned that, at least in C, that is just a Pre-compiler command to replace that whole #include line with the entire contents of the .h file, which basically does what we said before of putting the prototypes at the top. So, to the computer, options 2 and 3 are basically the same, they just appear different for us.
In Objective-C, you do not need to care about the order your declare methods, for the most part, so you do not generally need that advantage header files give. There are some reasons to forward declare methods, but they are much less common, and can be discussed later. In Objective-C, header files are more often used as an external interface. If another class will call your class, it should only call items mentioned in your header file. You also should in general only have #includes in your header file for things that are necessary for the header file to make sense, and any privately used ones, can be written in your implementation file. In Objective-C, your implementation file is a “.m” file, and your header file is still the familiar “.h” file.
Thanks for reading this post, and stay tuned for more from the front line of somebody learning Objective-C.