Introduction to iPhone development

It has been little more than 2 years since the iPhone was first announced and during that time it has managed to make a huge impact on the mobileindustry.

Introduction

Just recently, iPhone sales figures surpassed all windows mobile phones combined and in several markets the iPhone has been a top selling phone model. Together with the launch of App Store, Apple has managed to create a service delivery platform that attracts not only the hardcore users, but also the average Joe. A testament to this is the fact that App Store has had over one billion application downloads with over 50 000 applications available. This large potential customer base, combined with the advantage of having virtually no device fragmentation, makes it quite an attractive platform for mobile application developers. The business model is also lucrative, with Apple offering 70% of revenues from the store to instantly go to the seller of the app without having to pay for distribution or anything else than a one time fee. In this regard, the iPhone has certainly helped Apple put the Objective-C language in the limelight.

For the developer, the transition from higher level languages such as Java may
not be so simple as Objective-C has quite a unique syntax. The goal of this
article is to remedy that by going through the main concepts of Objective-C
from a Java perspective. Hopefully this will help you to get a quicker start in your
iPhone development. You should however be aware that it is equally important
to understand how to use the iPhone’s application frameworks in order to create
applications, this article only scratches the surface of the language you will use.

Objective-C from a Java perspective

If you are used to both working in C/C++ and Java you might soon recognize
Objective-C as a middle-ground language, meaning that it provides lower-level
mechanisms than Java while being a more manageable and higher-level language
than C/C++. The language is a strict superset of C, which means it’s possible
to write and compile normal C code using the Objective-C compiler. We also
use pointers (signified in code with an asterisk, *) to objects and not references,
like in Java. For object orientation Objective-C uses a syntax similar to that of
Smalltalk, which might take a little time to get used to if you haven’t seen it
before. Objective-C is a highly dynamic language, much like Ruby and Python,
where it’s possible to change the behavior at runtime. The compiler is quite
forgiving and before getting used to this you will likely discover more problems
during runtime than when using Java.

While some of the features in Objective-C are unique, many of them are
similar to those of Java only named differently. In order to ease the transition,
we will use Java terminology as much as possible and step by step build up a
small example in Objective-C that covers the basic features. In some cases the
examples will keep code from previous examples and in some only the change
will be presented to save space. Regardless, the new code is always in bold font.
Let’s get started.

Classes

Unlike Java which uses a single .java file, Objective-C separates class declaration
and definition into two files: .h and .m. The .h file is called the interface, which
shouldn’t be confused with Java interfaces (more on this later). Most importantly,
the interface file lists the methods and member variables that the class contains.
A minimal compilable .h file would look like this:

This piece of code simply declares an empty interface named MyClass which
you preferably should put in a file named “MyClass.h”. The space between the
“{}” signs is where we will put our member variable declarations and the space
right before the @end tag is where method declarations go. The .m file looks like
this:

It’s between the lines starting with @implementation and @end that we will
put our actual method implementations. Notice that there are no “{}” signs
since member variables are declared in the interface file. This minimal example
obviously doesn’t do much but it will compile and it it gives us something to
start with.

Similarly to Java, Objective-C has a superclass that most classes inherit from:
NSObject. But while we in Java are used to an implicit inheritance from this
class, we must here explicitly declare this in our .h files. To inherit a class, we
simply add a colon after the class name in our .h file followed by the name of
the class we wish to inherit:

Conceptually, NSObject has similarities to java.lang.Object. But it is also more
powerful in the sense that it provides some features that are only possible with the
reflection API in Java. As an example, NSObject allows you to take advantage of the
runtime and determine which methods are implemented. It also contains methods
that are needed for proper memory management such as retain and release which
we will look closer at later on.

Naming conventions

Objective-C does not provide any type of namespace functionality like Java does
with packages. Instead, to avoid name clashes, the best way is to use prefixes.
You will see this used heavily throughout the official APIs. NSString (a Foundation
class) and UITextField (of the UIKit framework) are two examples. This makes
it easy to see which classes are written by Apple. We recommend that you use
an abbreviation of your company as two upper case characters and prefix your
classes with that. If your company name is Acme, you could use AC as a prefix.

When programming in Objective-C it is advisable to follow the guidelines from
Apple about naming classes, methods and other building blocks. Typically we
want naming to be very expressive and also highly consistent. This contrasts
Java where, for example, some collection classes use addElement(…) and
sometimes add(…) to add new objects. Consistency makes it a lot easier to
learn the frameworks because they follow the same conventions. We also want
to be expressive and really explain in naming what the class or method does.
Java enforces conventions through JavaBeans standards, but Apple goes far
beyond that. For example, ACPeopleTableViewController would be a suitable
name for a Controller (MVC pattern) class that controls a TableView (standard
component) which contains People. When it comes to methods getters should
not be prefixed by “get” but rather have similar name as the property they are
fetching. If there is a property called defaultColor then the method to get it
is called -(NSColor*)color; not getColor();. There are many other naming
conventions and you’ll rather quickly get used to the standard ones.

Access Control

There are three types of access control you can set on your member variables:
private, protected, and public. They have the same effect as in Java. The syntax
for doing this is a bit different tough. Let’s add two member variables to our
header file and make these private:

We simply use the compiler directive “@private” and everything beneath it will
be private until either a “}” or another directive is found.

So how do I make my instance methods private? The answer is that you don’t
have to worry about that, since the language doesn’t formally support changing
the access type on methods. All methods are public!

Methods

The equivalent of calling methods in Java is defined as sending messages in
Objective-C. This is one of the big differences between the languages. On the
surface it may appear as we are doing the same thing only with different syntax:

But there is in fact a big underlying difference. The doSomething method in
the Java example must exist at compile time or the compilation will fail. The
same does not apply in the Objective-C case. The notion of sending a message
to an object implies that we will send something regardless of whether there is
a receiver or not and how the message together with parameters are handled is
determined at runtime.

Now let’s declare a method in our header file that will add two numbers:

The syntax may seem confusing at first but the elegance is displayed once the
method is used to pass a message:

Notice the readability of that method. Instead of guessing or reading
documentation for method signatures we know right away which parameter
goes where. Now lets add the implementation in the .m file:

Constructors

Objective-C doesn’t have the same concept of constructors as Java. Instead,
object creation is divided into two parts: allocation and initialization. There is
no special syntax reserved for object creation (i.e. new in Java). The methods
handling this are regular methods and are named alloc and init respectively. The
two calls are usually nested to allocate and initialize an object on a single line:

Notice the star in front of myObject. This is regular C syntax for declaring
a pointer. Now pointers are usually something that Java people like to avoid
since it can be the source of all kinds of troubles. Fortunately, if you stick to
using Objective-C you almost never have to use the star or any dereference
mechanism when actually using the objects. Just keep in mind that it has to be
there in the declaration.

The alloc method is a static method that resides in NSObject and should never
be overridden. It allocates memory and returns a new instance of the receiving
class. The init method on the other hand is an instance method and should be
overwritten. In fact, the default implementation does nothing but return itself.
The simplest form of init implementation usually looks like this:

We always call the parent’s init method and make sure we get something back.
Then we execute our initialize code and return self which is the Objective-C
equivalent of Java’s this.

Just like you often have multiple constructors in Java, you will likely have
more than one initializer in your Objective-C class that takes different types of
arguments. According to convention you should start the name of these methods
with “initWith”. Here’s an initializer that takes two numbers as parameters:

The convention also says that only one initializer should make the call to super.
It is often convenient to do this in the initializer with the most arguments, and
let the other initializers call that one. Let’s change the first initializer so it looks
like this:

Protocols

Protocols are essentially the same thing as Java interfaces but with added flexibility.
A class is not always required to implement all methods just to conform to the
protocol, some can be marked as optional. Furthermore, a class can conform to a
protocol by just implementing the required methods, even if it hasn’t explicitly
declared that it is implementing it. Let’s create our own protocol to indicate that
the example class can calculate something, and suitably call it Calculator. We
enter the following in a new .h named CalculatorProtocol.h.

The protocol declaration is pretty straight forward. The @required attribute
signifies that the method is mandatory to implement. We could also have written
@optional if we don’t want to force an implementation. It’s also possible to mix
required and optional methods. Now to show that our example class conforms
to this protocol we first change the .h file:

And then we add the implementation of our getCalculation method in the .m
file:

Where’s my garbage collector?

Unlike Java and desktop Objective-C development there is no garbage collector
available when creating applications for the iPhone. The reason for this is to
allow the best possible performance. This means that you will have to clean up
after yourself manually. Fortunately, the NSObject class contains functionality
to make manual memory management easier. Every object whose class inherits
from NSObject contains a so called retain count which is used to indicate how
many other objects that are using or “owning” it. If you own an object, you are
also responsible for releasing it when you are done, at which point the retain
count willl go down. When the retain count reaches 0 the system will assume it’s
safe to deallocate the memory for your object. So when is the object considered
“used”, i.e. when does the retain count go up? First of all, the retain count will
implicitly increase if you you create the object yourself by using a method name
beginning with “alloc”, “new” or contains “copy”. Secondly, you must explicitly
add one to the retain counter by calling the NSObject method “retain” whenever
you wish to take ownership of an object that you receive by other means, i.e. as
a parameter or from a getter method.

To reduce the retain count, or say that you no longer need the object in question,
you use [myObject autorelease] or [myObject release], where autorelease
signifies that the object should release later. To show how this works we add the
following to our example:

We need to retain newName in case we are passing the same object that is
currently assigned to name, or it might be deallocated. When releasing name it’s
possible that it’s not set, but it’s fine to call release on a nil object.

There are situations when you want to autorelease objects. For instance, if you
have a method that returns a NSString that is created inside the method:

If you run this code there’ll be problems. The formatted variable will be released
before it’s returned which means that whoever requested the NSString will get
a pointer to a freed object. The solution is to replace release with autorelease.
Objects that are sent autorelease will be added to an autorelease pool. When
the pool is deallocated release is sent to all objects it contains, including our NSString. The pool is created before events and deallocated when the event has
been handled. That way the formatted variable won’t be deallocated right away.

All objects that are not created using alloc, new or copy are automatically added
to the current autorelease pool. So if you don’t want to loose those objects you
need to retain them.

Many objects have convenience methods that return autoreleased objects, so
the easiest solution to our problem would be to avoid the alloc and instead use
a convenience method:

Manual memory management is usually one of the tougher parts to get used to
when coming from a “friendlier” language such as Java. It is important however
to get a good understanding in this area as it often can be the source of nasty
bugs.

Conclusions

That concludes our example and short introduction to Objective-C, the
language you need to master – or at least learn to use – in order to write great
iPhone applications. The syntax and some concepts differ a bit from Java, but
it’s relatively easy to pick up and get started with. There are many other areas
we haven’t even touched upon, such as the frameworks and tools provided by
Apple. Fortunately there’s a wealth of information available online at the iPhone
Dev Center, where you can read API references, download sample code, watch
tutorial guides and videos as well as discuss with other developers. In order to
develop applications for iPhone you need a Mac computer running Mac OS X
and register as a developer (for free) on Apple’s website. Good luck!

Christian Hedin
Stefan Li

Originally published in JayView.

This Post Has One Comment

  1. New iPhone developers will find the Q&A website StackOverflow.com insanely useful when trying to pick up the the details of Objective-C and the iPhone SDK.

Leave a Reply

Close Menu