Objective-C Programming/syntax

Objective-C is an object-oriented programming language, and is a layer over the C programming language. This means that if you know how to write C, there are only a few syntax changes to learn.

In this section, we will look at how we can implement classes and instantiate objects in Objective-C. If you are unfamiliar with object-oriented programming, see Objective-C concepts.

Basic syntax
If you have studied C, you can skip this section and proceed to the next section, A word on runtimes. If not, or if you're a little rusty, read on.

In C, code is contained within a function. Functions are composed of several statements, each of which are terminated by a semicolon. For example, a simple function in C to add two numbers may look like this:

This sample has the following lines:
 * 1) The function definition (which returns an int (integer), is named add, and takes two parameters, both of which are integers). // Integers are whole numbers like 6, 66 or 567 and not numbers with decimal places like 5.6.
 * 2) The opening function brace
 * 3) A variable declaration
 * 4) An assignment statement
 * 5) A return statement, which returns the value of c to the calling function/
 * 6) The closing function brace

For control flow, C and Objective-C use: The for, while, and do statements will continue execution of a loop until the condition is false. The switch and if statements jump to different statements depending on the condition.
 * 1) for (&lt;initial>;&lt;condition>;&lt;increment>)
 * 2) while (&lt;condition>)
 * 3) do ... while (&lt;condition>)
 * 4) switch (&lt;condition>)
 * 5) if  then { } [else ]

Objective-C does not implement or import any functions by default. Instead, they need to be imported by using the  preprocessor directive. (#include works too, but generally it is not used in Objective-C - #import works better because it won't import the same thing twice like #include can try to do)

A word on runtimes
Objective-C requires what is known as a runtime system to provide you with Objective-C features. The runtime takes care of the creation, management, and destruction of objects.

If you have the gcc compiler, you should have the Objective-C runtime already installed. Otherwise, you may have to install the runtime separately. Note that gcc is a compiler collection; the full install contains not only the C compiler, but also C++, Java, Objective-C and even Fortran-95 and Ada 2005 compilers. However, it is possible to install gcc only partially, for example only the C compiler. Therefore, the Objective-C runtime may or may not be installed with gcc. Check your distribution.

Two main systems are used to run Objective-C programs:
 * the GNU runtime, which is provided as a part of gcc on Unix and Unix-like operating systems;
 * the NeXT runtime, which is provided on NeXTSTEP, OPENSTEP, and Mac OS X operating systems.

This text assumes you are using the GNU runtime, but the two runtime systems are almost identical.

This text does not cover the OPENSTEP, Cocoa, or GNUstep frameworks, but the skills learned here will be helpful when developing with those systems.

Writing classes in Objective-C
Writing an Objective-C class requires a few design decisions before we start writing any code. Say we are writing a class to represent a point called Point in a two-dimensional plane.

We need to ask ourselves two questions:
 * 1) What data do we need to store and use? This relates to the instance variables we need to declare.
 * 2) What operations do we need to perform? This relates to the methods we need to define.

For this example, we'll use double variables for the x and y coordinates. We'll define a method to get both coordinates, and we'll define a method to get their distance from the origin.

The interface
Let's examine what each element of this interface means.

The @interface line says that we begin the declaration of the Point interface. We inherit from another class called Object. Objective-C provides you with a generic class, called Object. The Object class is a root class -- it does not inherit from another class. The <tt>Object</tt> class provides a set of methods that provide key functionality for an object to be used and recognized by the Objective-C runtime. As in C, we need to include <tt>Object</tt>'s header file, <tt>Object.h</tt>, before we can use the set of methods declared in the header.

If you don't explicitly inherit from some class, your class becomes a root class. (In Objective-C, there can be many root classes.) That's probably not what you want to do, because creating a root class is a very tricky and advanced topic that is only useful in very specific situations. In most cases, you will want to inherit from <tt>Object</tt> or some class that inherits from <tt>Object</tt>, etc. If you develop in NeXTStep / GNUstep / Cocoa, you will mostly be using another root class called <tt>NSObject</tt>, which provides different basic methods than <tt>Object</tt>.

The word <tt>import</tt> means that we only include the file once. This solves problems like recursive includes.

Anything between the braces in an interface declaration specifies the instance variables that the class has.

The <tt>@private</tt> line is a visibility modifier: it says that the instance variables after it are private, i.e. they are accessible only from the class that declares them. It is good practice to mark all your instance variables private: they contain the state of an object and they should never be changed except by the object itself.

The declarations for the methods come after the instance variables. This is a declaration for the method to set the x value. It's common Objective-C style to name the setter method with the same name as the variable it's setting.

The hyphen specifies an instance method (we'll look at these later). Then comes the name for the method (this method is called <tt>x:</tt> - note the colon), and the colon signifies an argument, called <tt>x_value</tt>, and is of type <tt>double</tt>.

The cast on the <tt>x_value</tt> argument is necessary, because unlike C, the default type is <tt>id</tt>, and not <tt>int</tt>. The type <tt>id</tt> is very special—it is a type that can hold any object whatsoever. The first cast is not strictly necessary, but should be used for clarity. The first cast tells us that the method <tt>x</tt> returns an object back.

This is another method named <tt>x</tt> (no colon), but it returns a <tt>double</tt>. This is the specification for the method that gets the value of the x variable. There is no conflict with the previous method because the types are different, and the previous method takes one argument whilst this takes none.

After all the methods and instance variables are specified, this symbol marks the end of the declaration.

The interface specification goes in a <tt>.h</tt> file—a header file. It's customary to call the file after the class, so we would create a file called <tt>Point.h</tt>.

The implementation
This is the implementation for the <tt>Point</tt> class. We implement the methods in the interface defined above. Let's have a look at each element of the implementation in turn.

Again, we import <tt>Point</tt>'s interface, just as we do in C.

This is a marker that identifies the beginning of the implementation.

This is a typical method implementation. We can use the <tt>x</tt> variable directly without having to declare it since it is already declared in the interface, and is accessible only to the methods of this class. The behaviour, in general, is like an ordinary C function. Here we assign the value of the argument <tt>x_value</tt> to the instance variable <tt>x</tt>.

The function then, returns the entire, current object as modified. The keyword <tt>self</tt> represents the current object.

Here is the simple method to get the value of the <tt>x</tt> variable. We simply return it.

The behaviour for the other methods should be similar to those above. The <tt>@end</tt> keyword ends the implementation.

The implementation specification goes in a <tt>.m</tt> file. It's customary to call the file after the class, so we would create a file called <tt>Point.m</tt>.

Using the objects
Since Objective-C comes from C, we write a <tt>main</tt> function to make use of the class that we just created. Here's one typical main function.

Let's examine what happens here.

We import the interface to <tt>Point</tt> so we can use it. We import <tt>stdio.h</tt> so we can use <tt>printf</tt>. This is a typical Objective-C method call: These are some typical instance method calls. We call <tt>point</tt>'s method <tt>x:</tt> and <tt>y:</tt>. In Objective-C terminology, we say that we send <tt>point</tt> a message to apply to the method <tt>x:</tt>.
 * <tt>Point *point</tt> declares, technically, a pointer to an instance of type <tt>Point</tt>. Actually, it may be best to think of this merely as a variable holding a <tt>Point</tt> object, but keep the pointer idea in mind.
 * <tt>[Point new]</tt> calls a method called <tt>new</tt>. The first half before the space represents the object we call the method on. The second half is the method name and arguments. The <tt>new</tt> method is called a class method, because it doesn't do something with respect to an instance of a class, it does something with respect to the class itself. The <tt>new</tt> method allocates memory and initializes the object, making it ready for use. There is no need to explicitly delete an object, as Objective-C keeps track of the number of references to a given object, and deallocates them as necessary.
 * NOTE: The <tt>new</tt> method is shorthand for <tt>alloc</tt> and <tt>init</tt> and may not always be available. If it is not, the object can be initialized and made ready for use in the following fashion: <tt>[[Point alloc] init]</tt>

These messages assign <tt>point</tt>'s <tt>x</tt> and <tt>y</tt> variables. Recall that the <tt>x:</tt> and <tt>y:</tt> methods had in them <tt>return self;</tt>. This means that we can chain the two messages together, as follows: [[point x:10.0] y:12.0];

The message <tt>[point x:10.0]</tt> returns an object, <tt>point</tt>, with its <tt>x</tt> variable set. Then on that object, the outer message assigns its <tt>y</tt> variable.

The <tt>printf</tt> statement has in it the method calls <tt>[point x]</tt>, which returns the value of the <tt>x</tt> variable for printing, <tt>[point y]</tt>, which does the same for the <tt>y</tt> variable for printing, and <tt>[point magnitude]</tt> which calculates the distance and returns that value.