C was conceived and created as a procedural programming language, whereas Objective-C was to be object-oriented, hence the name. In a procedural language, the code is focused around variables, data, and functions — how to store data and what to do with the data. In contrast, an object-orientated language focuses on creating objects, which are then used to do certain things, just like objects, or “things”, do in real life.
Object-orientated code seems to involve more work initially—there is a lot of “boilerplate” code for even the simplest objects. Fortunately, most of this code is already provided in Xcode’s templates, and the objects will quickly become more useful.
So what is an object? Put simply, it is a “thing.” Throughout this book, one of the objects that we will be creating will be a Die — the kind you might find in a board game. From the program’s perspective, the die is a “black box” — it hides its inner workings; the object performs any task that is asked of it (assuming that the object has been programmed to actually perform the task), and when it finishes, the object is no longer used. How the object performs its task is irrelevant, as far as the program itself is concerned.
Once you create an object, you can then tell your program to produce as many of them as you need. Therefore, your die object can create a pair of itself — a pair of dice.
These dice have traits, such as color, size, or the number of faces. You can also perform actions with these dice — you can roll one, or you can roll both of them. After rolling both of them, you would then add, or perhaps multiply, the resulting numbers.
From a higher-level viewpoint, all the program has to do is ask the dice to roll themselves, and report a total. The program does not have to know how the dice do that. In fact, if you were not the original creator of the die object, you wouldn’t either — and that’s perfectly fine.
Object-orientated programs allow developers to hide the inner workings of their program, while also making the program more efficient to run, as well as maintain. It has become the de facto programming language convention for most large programs, and likely will remain as such for years to come.
This post is part of the Learn Objective-C in 24 Days course.
Author: Feifan Zhou