O'Reilly logo

Learning iPhone Programming by Alasdair Allan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 4. Coding in Objective-C

Thus far, you’ve built a simple iPhone application and discovered that it’s not that hard to build apps for the iPhone or iPod touch. Let’s step back and take a broader look at the Objective-C language.

Objective-C is an object-oriented language that adds Smalltalk-style messaging to C. The language is a superset of the C language, providing constructs to allow you to define classes and objects. Once you get the hang of the Smalltalk-style syntax, if you’ve programmed in an object-oriented language before, things should look fairly familiar. However, there are some differences, and I discuss them in this chapter. One of the bigger differences, especially for those who are coming from a Java background, is in how Objective-C deals with memory management.

Declaring and Defining Classes

As is the case in almost all other object-oriented languages, in Objective-C classes provide the building blocks to allow encapsulation of data and methods that act on that data. Objects are specific instances of a class, and they contain their own instance data and pointers to the methods implemented by the class. Classes are specified in two pieces: the interface and the implementation. The interface contains the declaration of the class and is normally contained in a .h file. The implementation contains your actual code (the definition) and is normally contained in a .m file. We briefly discussed this in Chapter 3, but let’s take some time to look at it in more detail here.

Declaring a Class with the Interface

Let’s return to the declaration of the HelloWorldViewController class from Chapter 3, which illustrates a typical class interface. The interface begins with the @interface keyword, followed by the name of the class being declared and ending with a colon followed by the name of the base (or parent) class:

@interface HelloWorldViewController : UIViewController

An Objective-C class cannot inherit from multiple classes; however, the class it inherits from may in turn inherit from another class. In the case of HelloWorldViewController, its base class is UIViewController, which itself inherits from UIResponder, which inherits from NSObject, the root class of most Objective-C class hierarchies.


Objective-C allows objects to descend from any root class. Although NSObject is the most common root class, it is not the only one. For instance, NSProxy is also a root class. So, you cannot always assume that a given class is derived from NSObject.

After that first line, the instance variable declarations appear within curly braces. Following that, we have the declaration of properties and methods associated with the class. The class declaration is wrapped up with the @end keyword:

#import <UIKit/UIKit.h>1

@interface HelloWorldViewController : UIViewController {
    UIButton *button;
    UILabel *label;

@property (nonatomic, retain) IBOutlet UILabel *label;

-(IBAction)sayHello:(id) sender;


The #import statement is not technically part of the class declaration. Instead, this is a C preprocessor directive that avoids multiple inclusions of the same header file and is effectively equivalent to the C preprocessor directive #include <UIKit/UIKit.h>.

Defining a Class with the Implementation

The HelloWorldViewController implementation from Chapter 3 begins by importing the class interface in the .h file. The implementation begins with the @implementation declaration and ends with the @end declaration:

@implementation HelloWorldViewController



After the implementation begins, we must synthesize the accessor for the properties we declared in our interface file and implement the declared methods:

#import "HelloWorldViewController.h"

@implementation HelloWorldViewController

@synthesize label;

-(IBAction) sayHello:(id) sender {
    label.text = @"Hello World";

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

- (void)viewDidUnload {

- (void)dealloc {
    [label release];
    [button release]
    [super dealloc];


Now that you’ve taken a quick look at the structure of an interface and implementation, let’s take a detailed look at the individual parts.

Object Typing

When instance variables are themselves objects—for instance, when the HelloWorldViewController class declares UIButton and UILabel variables—you should always use a pointer type. However, Objective-C adds an interesting twist: it supports both strongly typed and weakly typed declarations. Here’s a strongly typed declaration:

UIButton *button;

Here we declare anObject. In the first instance we use strong typing, declaring it as an object of the class SomeClass.

Here’s a weakly typed version of the declaration, where it is declared as an object of class id:

id button;

The id class is a generic C type that Objective-C uses to represent an arbitrary object; it’s a general type representing any type of object regardless of class and can be used as a placeholder for both a class and a reference to an object instance. All objects therefore are of type id. This can prove very useful; you can imagine that if you wanted to build a generic class implementing a linked list, the type of object held in each node would be of type id, since you’d then be able to store any type of object.


The declaration of properties using the @property compiler directive is a convenience to avoid the declaration and, usually, the implementation of accessor methods for member variables. You can think of a property declaration as the equivalent of declaring accessor methods. You can also dictate how the automatically generated accessor methods behave by declaring custom attributes (see the sidebar ). In the HelloWorldViewController class, we declare the property to be (nonatomic, retain):

@property (nonatomic, retain) IBOutlet UILabel *label;

We can also declare both of our properties to be an IBOutlet. While not formally part of the list of attributes for an @property declaration, IBOutlet denotes that this property is an Interface Builder outlet. I talked about outlets briefly in Chapter 3 and will discuss them in more detail later.

Synthesizing Properties

When you declare an @property in the class interface, you must also synthesize the property (unless you wish to implement the getter and setter methods yourself) using the @synthesize declaration, as we do for the label property in the HelloWorldViewController class:

@synthesize label;

This asks the compiler to generate the accessor methods according to the specification in the property declaration, and much reduces the amount of boilerplate code that you have to write yourself.

The Dot Syntax

When you declare a member variable as a property and synthesize the declared accessors using the @synthesize declaration in the @implementation of the class, you can (entirely optionally) make use of some syntactic sugar that Objective-C provides, called the dot syntax, as an alternative to using the automatically generated accessor methods directly. For instance, this lets us do the following:

label.text = @"Hello World";

instead of doing this (note that Objective-C capitalized the t in text when it generated the accessor method):

[label setText:@"Hello World"];

The dot syntax is arguably somewhat neater and easier to read.

Declaring Methods

We declare one method in the HelloWorldViewController class, called sayHello:.

#import <UIKit/UIKit.h>

@interface HelloWorldViewController : UIViewController {
    UILabel    *label;
    UIButton   *button;

@property (nonatomic, retain) IBOutlet UILabel *label;

-(IBAction)sayHello:(id) sender;


The minus sign in front of the method indicates the method type, in this case an instance method. A plus sign would indicate a class method. For example:

+(void)aMethod:(id) anObject;

The sayHello: method takes an id object as an argument and is flagged as an IBAction for Interface Builder. When compiled, IBAction is replaced with void and IBOutlet is removed; these compiler directives are simply used to flag methods and variables to Interface Builder. This method is passed a generic id object as an argument since we intended it to be triggered by a UI event, and we want to leave it open as to what sort of UI element will be used. Under our UI, it’s triggered when the user clicks the “Push me!” button in the UI, and this id object will be the UIButton that the user clicked to trigger the HelloWorld event application. We can recover the UIButton object by casting the sender object to a UIButton:

UIButton * theButton = (UIButton *)sender;

It’s a standard practice in Objective-C to call such objects sender. If we were unsure of the underlying type of an id object, we could check the type using the isKindOfClass method:

if([thisObject isKindOfClass:[anotherObject class]]) { ... }

Calling Methods

If you want to call a method exposed by an object, you do so by sending that object a message. The message consists of the method signature, along with the parameter information. Messages are enclosed in square brackets; the object receiving the message is on the left and the parameters are on the right, with the parameter following a colon. If the method accepts more than one argument, this is explicitly named, and the second parameter follows a second colon. This allows multiple methods with the same name and argument types to be defined.

[anObject someMethod];
[anObject someMethod: anotherObject];
[anObject someMethod: anotherObject withAnotherArgument: yetAnotherObject];

The name of the method is the concatenation of the method name and any additional named arguments. Hence in the preceding code we have someMethod: and someMethod:withAnotherArgument:. This may seem odd to people coming in from other languages, which usually have much terser naming conventions, but in general Objective-C method names are substantially more self-documenting than in other languages. Method names contain prepositions and are made to read like sentences. The language also has a fairly entrenched naming convention, which means that method names are fairly regular.


While Objective-C method names are long, Xcode will perform code completion as you type. Press Return to accept its suggestion, or F5 to present a pop-up list of matching methods. Pressing Ctrl-/ will step you through the parameters of the method.

Methods can return output, as shown here:

output = [anObject someMethodWithOutput: anotherObject];

And they can be nested, as in the following:

output = [anObject someMethodWithOutput: [anotherObject someOtherMethod]];

When I originally started writing in Objective-C, one of the main problems I had with the language was the way it dealt with method calls. For those of us who are coming from more utilitarian languages, the behavior of Objective-C in this regard does seem rather strange. Although Objective-C code can be valid and not follow the rules I’ve described here, modern Objective-C is not really separable from the Cocoa framework, and Cocoa rules and conventions have become Objective-C’s rules and conventions.

Calling Methods on nil

In Objective-C, the nil object is functionally equivalent to the NULL pointer found in many other C-derived languages. However, unlike most of these languages, it is permissible to call methods on nil without causing your application to crash. If you call a method on (although in Objective-C we are actually passing a message to) the nil object type, you will get nil returned.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required