Having increased our knowledge of Objective-C, we are ready to discuss how to create a program with a Graphical User Interface (GUI). I have to confess something here. Objective-C is actually an extension of a programming language called C. Most of what we have discussed so far is just plain C. So how does Objective-C differ from plain C? It is in the "Objective" part. Objective-C deals with abstract notions known as objects.
Up until now we have mainly dealt with numbers. As you learned, Objective-C natively supports the concept of numbers. That is, it let you create numbers in memory and manipulate them using math operators and mathematical functions. This is great when your application deal with numbers (e.g. a calculator). But what if your application is, say, a music jukebox that deals with things like songs, playlists, artists etc.? Or what if your application is an air traffic control system that deals with planes, flights, airports etc.? Wouldn't it be nice to be able to manipulate such things with Objective-C as easily as you manipulate numbers?
This is where objects kick in. With Objective-C, you can define the kind of objects you are interested to deal with, and then write applications that manipulate them.
As an example, let's take a look at how windows are handled within a program written in Objective-C, such as Safari. Take a look at an open Safari window of your Mac. At the top left, there are three buttons. The red one is the close button. So what happens if you close a window by clicking that red button? A message is sent to the window. In response to this message, the window executes some code in order to close itself.

A close message is sent to the window
The window is an object. You can drag it around. The three buttons are objects. You can click them. These objects have a visual representation on screen, but this is not true of all objects. For instance, the object that represents a connection between Safari and a given web site does not have a visual representation on screen.

An object (e.g. the window) can contain other objects (e.g. the buttons)
You can have as many Safari windows as you want. Do you think that Apple's programmers:
Of course, the answer is b. They created some code, called a class, which defines what a window is and how it should look and behave. When you create a new window, it is actually this class that creates the window for you. This class represents the concept of a window, and any particular window is actually an instance of that concept (in the same way that 76 is an instance of the concept of a number).
The window you created is present at a certain location on the screen of your Mac. If you minimize the window to the Dock, and make it reappear, it will take exactly the same position on the screen that it had before. How does this work? The class defines variables suitable for remembering the position of the window on the screen. The instance of the class, i.e. the object, contains the actual values for these variables. So, each window object contains the values of certain variables, and different window objects will in general contain different values for those variables.
The class not only created the window object, but also gave it access to a series of actions it can perform. One of those actions is close. When you click the "close" button of a window, the button sends a close message to that window object. The actions that can be performed by an object are called methods. As you will see, they resemble functions very closely, so you will not have much trouble learning to use them if you have followed us so far.
When the class creates a window object for you, it reserves memory (RAM) to store the position of the window and some other information. However, it does not make a copy of the code to close the window. That would be a waste of computer memory because this code is the same for every window. The code to close a window needs to be present only once, but every window object has access to that code belonging to the window class.
As before, the code you are about to see in this chapter contains some lines for reserving memory and releasing it back to the system. As indicated earlier, we will not discuss this advanced subject until much later. Sorry.
We are going to create an application with two buttons and a text field. If you press one button, a value is entered into the text field. If you press the other button, another value is put into the text field. Think of it as a two-button calculator that can't do calculations. Of course, once you learn more you can figure out how to create a calculator for real, but I like small steps.

A sketch of the application we want to create
If one of the buttons of our app is pressed, it will send a message. This message contains the name of a method to be executed. This message is sent to, well, to what? In case of the window, the close message was sent to that window object, which was an instance of the window class. What we need now is an object that is capable of receiving a message from each of the two buttons, and can tell the text field object to display a value.
So, we first have to create our own class, and then create an instance of it. That object will be the receiver of the message from the buttons (Please refer to the sketch below). Like a window object, our instance is an object, but in contrast to a window object, we can't see our instance on the screen when we run the program. It is just something in the memory of the Mac.
When our instance receives a message sent by one of the (two) buttons, the appropriate method is executed. The code of that method is stored in the class (not in the instance itself). Upon execution, this method will reset the text in the text field object.
How does the method in our own class know how to reset the text in a text field? Actually, it doesn't. But the text field itself knows how to reset its own text. So we send a message to the text field object, asking it to do just that. What kind of message should that be? Of course, we need to specify the name of the recipient (i.e. the text field object in our window). We also need to say, in the message, what we want the recipient to do. We specify that by using the name of the method that the text field will have to execute upon receipt of the message. (Of course, we need to know what methods text fields can execute, and what they are called.) We also need to tell the text field object what value to display (depending on the button clicked). So, the message sending expression not only contains the name of the object and the method name, but also an argument (value) to be used by the method of the text field object.

A sketch of message exchanges between the objects in our application
Here is the general format of how to send messages in Objective-C, both without [1.1] and with [1.2] an argument:
//[1] [receiver message]; [receiver messageWithArgument:theArgument];
As you can see in each of these statements, the whole shebang is placed between square brackets and the eternal semi-colon is present as the finishing touch. Between the brackets, the receiving object is mentioned first, followed by the name of one of its methods. If the method being called requires one or more values, they must be provided as well [1.2].
Let's see how this works for real. Start up Xcode to create a new project. Select Cocoa Application under the Application heading. Give your project a name, like "My First App" (by convention, the name of your GUI application should start with a capital). In the Groups & Files frame of the Xcode window that appears, open the Resources folder. Double-click on MainMenu.xib.

Prior to Xcode 3, xib files were known instead as nib files, for NeXT Interface Builder. If you are using an older version of Xcode, you may see a MainMenu.nib file instead. This detail is not important - to all intents and purposes, they are the same thing.
Another program, Interface Builder, will start-up. As a lot of windows appear, you may want to choose Hide Others from the File menu. You will see three windows. The one named "Window" is the window that the users of your application will see. It is a bit big, so you may want to resize it. To the right of the window "Window", there is a window named "Library". It is a kind of repository for all kinds of objects you can have in your GUI and is known as the "Library palette". Select the "Objects" item in the list at the top of this window and drag two Buttons, one at a time, onto the GUI window "Window". Similarly drag one text Label having the text "Label" onto the GUI window.

Dragging GUI objects from the palettes window to your application's window.
Behind the scenes, the action of dragging a button from the palettes window to your application's window creates a new button object and puts it in your window. The same goes on for the text field and any other objects you might drag to your window from the palettes window.
Note that if you hold your cursor over an icon in the palettes window, a name will be displayed, such as NSButton or NSTextView. These are the names of classes provided by Apple. Later in this chapter we will see how we can find the methods of these classes, which we need to perform the necessary actions in our program.
Don't forget to save your nib regularly so that Xcode and IB are able to stay in sync.
Arrange the objects you dragged onto the window "Window" nicely. Resize them as you see fit. Change the text of the button objects by double-clicking them, one at a time. I invite you to explore the palettes window after we have finished this project to get a grip on how to add other objects to your window.
To change the properties of an object, select it and press Cmd-Shift-I. Explore this as well. For example, select the window "Window" (you can see it gets selected in the xib window) and press Cmd-Shift-I. If the title bar the top reads Window Attributes, you can set a tick for Textured, and this gives your window a metal look. You will find that you can customize the look of your application to a large extent without writing a single line of code!

Our window in Interface Builder, along with its inspector
Switch back to Xcode now. In your project window, if you open the Classes folder in the Groups & Files pane, you will see that there are two items with names starting with "My_First_Application_AppDelegate". These two files are the basic class that Xcode has created automatically for you. The file that ends in ".h" is the Header or Interface file for the class. The one that ends in ".m" is the Main or Implementation file for the class.

The Application Delegate class that is included with every new Cocoa application.
Every Cocoa application needs at least one class to do anything useful. By convention, the basic class is known as the Delegate, because it can implement a set of Delegate methods to customise the behaviour of Cocoa's NSApplication class. More about this later.
Let's look a bit deeper into how classes work.
To save a lot of programming effort, it would be nice if you could build on what others have already built, instead of writing everything from scratch. If you, for example, wanted to create a window with special properties (capabilities), you would need to add just the code for these properties. You wouldn't need to write code for all other behavior, such as minimizing or closing a window. By building on what other programmers have done, you would inherit all these kinds of behavior for free. And this is what makes Objective-C so different from plain C.
How is this done? Well, there is a window class (NSWindow), and you could write a class that inherits from that class. Suppose you add some behavior to your own window class. What happens if your special window receives a "close" message? You didn't write any code for that, and didn't copy such code into your class either. Simple, if the class of the special window doesn't contain the code for a particular method, the message is transferred automatically to the class from which the special window class inherits (its "superclass"). And if necessary, this goes on until the method is found (or it reaches the top of the hierarchy of inheritance.)
If the method cannot be found, you sent a message that can't be handled. It is like requesting a garage to change the tires of your sleigh. Even the boss of the garage can't help you. In such cases Objective-C will signal an error.
What if you want to implement your own behavior for a method already inherited from your superclass? That is easy, you can override particular methods. For example, you could write code that, on clicking the close button, would move the window out of view before actually closing it. Your special window class would use the same method name for closing a window as the one defined by Apple. So, when your special window receives a close message, the method executed is yours, and not Apple's. So, now the window would move out of sight, before being closed for real.
Hey, closing a window for real was already programmed by Apple. From inside our own close method, we can still invoke the close method implemented by our superclass, although it requires a slightly different call to make sure our own close method is not called recursively.
//[2] - (void) close:(id)sender { // Code to move the window out of sight here. [super close]; // Send the close message to the superclass. }
King of the hill, among classes, is the class named NSObject. Nearly all the classes you will ever create or use will be subclasses of NSObject, directly or indirectly. For example the NSWindow class is a subclass of the NSResponder class, which is itself a subclass of NSObject. The NSObject class defines the methods common to all objects (e.g. generating a textual description of the object, asking the object whether it is able to understand a given message etc.)
Before I bore you with too much theory, let's see how to create a class.
Go to the your Xcode project and select New File from File menu. Choose an Objective-C class from the list, make it an NSObject subclass, then click Next. I named mine "MFAExampleClass". Click Finish.

Creating the MFAExampleClass class
Once you have clicked Finish, you should see two new files in your Groups & Files pane.
The first three capitals of MFAExampleClass stand for My First Application. You can invent class names as you like. By convention, all class names begin with one or more capital letters, and they may not contain any spaces. Once you start writing your own applications, we recommend that you choose a two or three letter prefix that you'll use for all your classes in order to avoid confusion with existing class names. However, don't use NS, as this may confuse you later on. NS is reserved for Apple's classes. It stands for NeXTStep, NeXTStep being the operating system Mac OS X was based on when Apple bought NeXT, Inc.
The CocoaDev wiki contains a list of other prefixes to avoid. You should check it when choosing your own prefix: http://www.cocoadev.com/index.pl?ChooseYourOwnPrefix
When creating a new class you should give it a name that conveys useful information about that class. For instance, we've already seen that in Cocoa the class used to represent windows is named NSWindow. Another example is the class that is used to represent colors, which is named NSColor. In our case, the MFAExampleClass class we are creating is just here to illustrate the way objects communicate together in an application. This is why we gave it a generic name with no special meaning.
Back in Interface Builder, go to the Library palette and choose Objects & Controllers from the top menu. Then drag an Object (blue cube) from the palette to the MainMenu.xib class.

Instantiating a new object
Next, select the Identity button in the Inspector palette (Cmd-6), then choose MFAExampleClass from the Class pop-up menu. We have now instantiated our MFAExampleClass class in Xcode into an object in our xib file. This will allow our code and our interface to communicate.

Setting the identity of our object instance
Our next step is to create connections between the buttons (from which messages are sent) to our MFAExampleClass object. In addition, we are going to create a connection back from the MFAExampleClass object to the text field, because a message will be sent to the text field object. An object has no way of sending a message to another object if it doesn't have a reference to the other object. By making a connection between a button and our MFAExampleClass object, we are providing that button with a reference to our MFAExampleClass object. Using this reference, the button will be able to send messages to our MFAExampleClass object. Likewise, establishing a connection from our object to the text field will allow the former to message the latter.
Let us again go through what the application has to do. Each of the buttons can send, when clicked, a message corresponding to a particular action. This message contains the name of the method of the class MFAExampleClass that has to be executed. The message is sent to the instance of the MFAExampleClass class we've just created, the MFAExampleClass object. (Remember: object instances themselves don't contain the code to perform the action, but the classes do.) So, this message sent to the MFAExampleClass object triggers a method of the class MFAExampleClass to do something: in this case, sending a message to the text field object. Like every message, this one consists of the name of a method (which the text field object will have to execute). In this case, the method of the text field object has the task of displaying a value, and that value has to be sent as part of the message (called an "argument", remember?), along with the name of the method to invoke on the text field.
Our class needs two actions (methods), which will be called by the (two) button objects. Our class needs one outlet, a variable for remembering which object (i.e., the text field object) is to be sent a message.
Open the Library palette, and select the Classes tab at the top of the window. This will show you all the Classes in the Cocoa Frameworks and their attributes. At the bottom of the window is a search field. Begin typing MFAExampleClass in this field and you will see the MFAExampleClass displayed in the first pane.

MFAExampleClass in the class library
In the palette, in the Action section, click the Add (+) button to add an action (i.e., an action method) to the MFAExampleClass class. Replace the default name provided by Interface Builder by a more meaningful name (for example, you can enter "setTo5:" because we will program this method to display the number 5 in the text field). Add another method, and give it a name (for example "reset:", because we will program it to display the number 0 in the text field). Note that our method names both end with a colon (":"). More about this later.

Adding action methods to the MFAExampleClass
Now select the Outlet tab, add an outlet and give it a name (for example "textField").

Adding outlets to the MFAExampleClass
Before establishing connections between objects, we are going to give meaningful names to our two buttons. Since the first one is going to ask our Example Class instance to display the number 5 in the text field, we name it "Set to 5" (we already learned how to change the name of a button: double click on its name on-screen, and then enter the new name). Likewise, we name the second one "Reset". Note that this step of giving this button a particular name is not required for our program to work correctly. It is just that we want our user interface to be as descriptive as possible to the end-user.
Now we are ready to create the actual connections between
To create the connections, press the Control key on you keyboard and use the mouse to drag from the "Set to 5"" button to the MFAExampleClass instance in the MainMenu.xib window (don't do it the other way around!). A line representing the connection will appear on screen, and a menu will pop up on the object instance icon. Choose "setTo5:" from the list.

Establishing the connection
Now the button holds a reference to our MFAExampleClass object, and will send it the setTo5: message whenever it is pressed.
You can now connect the "Reset" button to the MFAExampleClass object by applying the same process.
To create the connection between the MFAExampleClass object and the text field, start from the MFAExampleClass object and control-drag to the text field object. Click "textField" in the menu to assign the connection.
What was this all about? Well, as you will see in a minute, you have just in effect created some code without writing a single line.
First, make sure MFAExampleClass is selected in the MainMenu.xib window. Go to the File menu in Interface Builder and choose Write Class Files. Interface Builder then asks you where you want your generated file to be put on disk. Navigate to the project folder of our application and overwrite the MFAExampleClass class that exists there. Make sure you set the Language pop up to Objective-C and check "Create '.h file". Replace the existing class files when prompted.

Now, if you switch back to Xcode, you'll see the generated files in your project window, inside the Classes group. If they appear in the Resources group, or a different group, simply select and then drag them to the Classes group. Click on the Editor toolbar button, then choose MFAExampleClass.h.

The generated files appear in our Xcode project
Let's go back for a moment to Chapter 3, where we discussed functions. Do you remember the function header [11.1]? It was a kind of warning for the compiler to tell it what it could expect. One of the two files we have just created is named MFAExampleClass.h, and it is a header file: it contains info about our class. For example, you'll recognize that there is a line [3.5] containing NSObject, which line means that our class inherits from the NSObject class.
//[3] /* MFAExampleClass */ #import <cocoa/cocoa.h> // [3.2] @interface MFAExampleClass : NSObject { IBOutlet id textField; // [3.7] } - (IBAction)reset:(id)sender; - (IBAction)setTo5:(id)sender; @end
You will see that there is one outlet [3.7] to the text field object. id indicates object. "IB" stands for Interface Builder, the program you used to create this code.
IBAction [3.9, 3.10] is equivalent to void. Nothing is returned to the object that sends the message: the buttons in our program do not get a reply from the MFAExampleClass object in response to their message.
You can also see there are two Interface Builder Actions. These are two methods of our class. Methods are quite like functions, which we already know, but there are differences. More on that later.
#import <Foundation/Foundation.h> instead of line [3.2], The former is for non-GUI apps, the latter for GUI-apps.
Now let's check out the second file, MFAExampleClass.m. Again we get a lot of code for free.
//[4] #import "MFAExampleClass.h" @implementation MFAExampleClass - (IBAction)reset:(id)sender // [4.5] { } - (IBAction)setTo5:(id)sender { } @end
First of all, the MFAExampleClass.h header file is imported, so the compiler knows what to expect. Two methods can be recognized: reset: and setTo5:. These are the methods of our class. They are similar to functions in that you need to put your code between the curly braces. In our application, when a button is pressed, it sends a message to your MFAExampleClass object, requesting the execution of one of the methods. We do not have to write any code for that. Making the connections between the buttons and the MFAExampleClass object in Interface Builder is all what is required. However, we do have to implement the two methods, i.e. we need to write the code that performs their function. In this case, these methods do nothing but send a message each from our MFAExampleClass object to the textField object, so we provide the statements [5.7, 5.12].
//[5] #import "MFAExampleClass.h" @implementation MFAExampleClass - (IBAction)reset:(id)sender { [textField setIntValue:0]; // [5.7] } - (IBAction)setTo5:(id)sender { [textField setIntValue:5]; // [5.12] } @end
As you can see, we send a message to the object referenced by the textField outlet. Since we connected this outlet to the actual text field, using Interface Builder, our message will be sent to the correct object. The message is the name of a method, setIntValue:, together with an integer value. The setIntValue: method is capable of displaying an integer value in a text field object. In the next chapter we will tell you how we found out about this method.
You are now ready to compile your application and launch it. As usual press the Build and Go button in the Xcode toolbar. It will take a few second for Xcode to build the application and to launch it. Eventually, the application will appear on screen and you'll be able to test it.

Our application running
In short, you have just created a (very basic) application, for which you had to write just two lines of code yourself!