www.oreilly.com/go/safarienabled
AFASLZG
jpyoung
Programming in Objective-C 2.0, Second Edition
by Stephen G. Kochan
Publisher: Addison-Wesley Professional
Pub Date: December 29, 2008
Print ISBN-10: 0-321-56615-7
Print ISBN-13: 978-0-321-56615-7
Web ISBN-10: 0-321-60555-1
Web ISBN-13: 978-0-321-60555-9
Pages: 624
We Want to Hear from You!
As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what we're
doing right, what we could do better, what areas you'd like to see us publish in, and any other words of wisdom you're willing to pass our
way.
You can email or write me directly to let me know what you did or didn't like about this book—as well as what we can do to make our
books stronger.
Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I
receive, I might not be able to reply to every message.
When you write, please be sure to include this book's title and author, as well as your name and phone or email address. I will carefully
review your comments and share them with the author and editors who worked on the book.
E-mail:
Mail:
Mark Taber
Associate Publisher
Pearson Education
800 East 96th Street
Indianapolis, IN 46240 USA
Reader Services
Visit our website and register this book at www.informit.com/register for convenient access to any updates, downloads, or errata that
might be available for this book.
1. Introduction
Dennis Ritchie at AT&T Bell Laboratories pioneered the C programming language in the early 1970s. However, this programming
language did not begin to gain widespread popularity and support until the late 1970s. This was because, until that time, C compilers
were not readily available for commercial use outside of Bell Laboratories. Initially, this growth in popularity was also partly spurred by
the equal, if not faster, growth in popularity of the UNIX operating system, which was written almost entirely in C.
Brad J. Cox designed the Objective-C language in the early 1980s. The language was based on a language called SmallTalk-80.
Objective-C was layered on top of the C language, meaning that extensions were added to C to create a new programming language that
enabled objects to be created and manipulated.
NeXT Software licensed the Objective-C language in 1988 and developed its libraries and a development environment called
NEXTSTEP. In 1992, Objective-C support was added to the Free Software Foundation's GNU development environment. The
copyrights for all Free Software Foundation (FSF) products are owned by the FSF. It is released under the GNU General Public License.
In 1994, NeXT Computer and Sun Microsystems released a standardized specification of the NEXTSTEP system, called OPENSTEP.
The Free Software Foundation's implementation of OPENSTEP is called GNUStep. A Linux version, which also includes the Linux
kernel and the GNUStep development environment, is called, appropriately enough, LinuxSTEP.
On December 20, 1996, Apple Computer announced that it was acquiring NeXT Software, and the NEXTSTEP/OPENSTEP
environment became the basis for the next major release of Apple's operating system, OS X. Apple's version of this development
environment was called Cocoa. With built-in support for the Objective-C language, coupled with development tools such as Project
Builder (or its successor Xcode) and Interface Builder, Apple created a powerful development environment for application development
on Mac OS X.
In 2007, Apple released an update to the Objective-C language and labeled it Objective-C 2.0. That version of the language is covered in
this second edition of the book.
When the iPhone was released in 2007, developers clamored for the opportunity to develop applications for this revolutionary device. At
first, Apple did not welcome third-party application development. The company's way of placating wannabe iPhone developers was to
allow them to develop web-based applications. A web-based application runs under the iPhone's built-in Safari web browser and requires
the user to connect to the website that hosts the application in order to run it. Developers were not satisfied with the many inherent
limitations of web-based applications, and Apple shortly thereafter announced that developers would be able to develop so-called native
applications for the iPhone.
A native application is one that resides on the iPhone and runs under the iPhone's operating system, in the same way that the iPhone's
built-in applications (such as Contacts, iPod, and Weather) run on the device. The iPhone's OS is actually a version of Mac OS X, which
meant that applications could be developed and debugged on a MacBook Pro, for example. In fact, Apple soon provided a powerful
Software Development Kit (SDK) that allowed for rapid iPhone application development and debugging. The availability of an iPhone
simulator made it possible for developers to debug their applications directly on their development system, obviating the need to
download and test the program on an actual iPhone or iPod Touch device.
What You Will Learn from This Book
When I contemplated writing a tutorial on Objective-C, I had to make a fundamental decision. As with other texts on Objective-C, I
could write mine to assume that the reader already knew how to write C programs. I could also teach the language from the perspective
of using the rich library of routines, such as the Foundation and Application Kit frameworks. Some texts also take the approach of
teaching how to use the development tools, such as the Mac's Xcode and Interface Builder.
I had several problems adopting this approach. First, learning the entire C language before learning Objective-C is wrong. C is a
procedural language containing many features that are not necessary for programming in Objective-C, especially at the novice level. In
fact, resorting to some of these features goes against the grain of adhering to a good object-oriented programming methodology. It's also
not a good idea to learn all the details of a procedural language before learning an object-oriented one. This starts the programmer in the
wrong direction, and gives the wrong orientation and mindset for fostering a good object-oriented programming style. Just because
Objective-C is an extension to the C language doesn't mean you have to learn C first.
So I decided neither to teach C first nor to assume prior knowledge of the language. Instead, I decided to take the unconventional
approach of teaching Objective-C and the underlying C language as a single integrated language, from an object-oriented programming
perspective. The purpose of this book is as its name implies: to teach you how to program in Objective-C 2.0. It does not profess to teach
you in detail how to use the development tools that are available for entering and debugging programs, or to provide in-depth instructions
on how to develop interactive graphical applications with Cocoa. You can learn all that material in greater detail elsewhere, after you've
learned how to write programs in Objective-C. In fact, mastering that material will be much easier when you have a solid foundation of
how to program in Objective-C. This book does not assume much, if any, previous programming experience. In fact, if you're a novice
programmer, you should be able to learn Objective-C as your first programming language.
This book teaches Objective-C by example. As I present each new feature of the language, I usually provide a small complete program
example to illustrate the feature. Just as a picture is worth a thousand words, so is a properly chosen program example. You are strongly
encouraged to run each program (all of which are available online) and compare the results obtained on your system to those shown in
the text. By doing so, you will learn the language and its syntax, but you will also become familiar with the process of compiling and
running Objective-C programs.
How This Book Is Organized
This book is divided into three logical parts. Part I, "The Objective-C 2.0 Language," teaches the essentials of the language. Part II, "The
Foundation Framework," teaches how to use the rich assortment of predefined classes that form the Foundation framework. Part III,
"Cocoa Programming and the iPhone SDK," gives you an overview of Cocoa's Application Kit framework and then walks you through
the process of developing a simple iPhone application using the UIKit framework, and developing and debugging the code with Xcode
and Interface Builder.
A framework is a set of classes and routines that have been logically grouped together to make developing programs easier. Much of the
power of programming in Objective-C rests on the extensive frameworks that are available.
Chapter 2, "Programming in Objective-C," begins by teaching you how to write your first program in Objective-C.
Because this is not a book on Cocoa programming, graphical user interfaces (GUIs) are not extensively taught and are hardly even
mentioned until Part III. So an approach was needed to get input into a program and produce output. Most of the examples in this text
take input from the keyboard and produce their output in a window: a Terminal window if you're using gcc from the command line, or
a Console window if you're using Xcode.
Chapter 3, "Classes, Objects, and Methods," covers the fundamentals of object-oriented programming. This chapter introduces some
terminology, but it's kept to a minimum. I also introduce the mechanism for defining a class and the means for sending messages to
instances or objects. Instructors and seasoned Objective-C programmers will notice that I use static typing for declaring objects. I think
this is the best way for the student to get started because the compiler can catch more errors, making the programs more self-
documenting and encouraging the new programmer to explicitly declare the data types when they are known. As a result, the notion of
the id type and its power is not fully explored until Chapter 9, "Polymorphism, Dynamic Typing, and Dynamic Binding."
Chapter 4, "Data Types and Expressions," describes the basic Objective-C data types and how to use them in your programs.
Chapter 5, "Program Looping," introduces the three looping statements you can use in your programs: for, while, and do.
Making decisions is fundamental to any computer programming language. Chapter 6, "Making Decisions," covers the Objective-C
language's if and switch statements in detail.
Chapter 7, "More on Classes," delves more deeply into working with classes and objects. Details about methods, multiple arguments to
methods, and local variables are discussed here.
Chapter 8, "Inheritance," introduces the key concept of inheritance. This feature makes the development of programs easier because you
can take advantage of what comes from above. Inheritance and the notion of subclasses make modifying and extending existing class
definitions easy.
Chapter 9 discusses three fundamental characteristics of the Objective-C language. Polymorphism, dynamic typing, and dynamic binding
are the key concepts covered here.
Chapters 10–13 round out the discussion of the Objective-C language, covering issues such as initialization of objects, protocols,
categories, the preprocessor, and some of the underlying C features, including functions, arrays, structures, and pointers. These
underlying features are often unnecessary (and often best avoided) when first developing object-oriented applications. It's recommended
that you skim Chapter 13, "Underlying C Features," the first time through the text and return to it only as necessary to learn more about a
particular feature of the language.
Part II begins with Chapter 14, "Introduction to the Foundation Framework," which gives an introduction to the Foundation framework
and how to access its documentation.
Chapters 15–19 cover important features of the Foundation framework. These include number and string objects, collections, the file
system, memory management, and the process of copying and archiving objects.
By the time you're done with Part II, you will be able to develop fairly sophisticated programs in Objective-C that work with the
Foundation framework.
Part III starts with Chapter 20, "Introduction to Cocoa." Here you'll get a quick overview of the Application Kit that provides the classes
you need to develop sophisticated graphical applications on the Mac.
Chapter 21, "Writing iPhone Applications," introduces the iPhone SDK and the UIKit framework. This chapter illustrates a step-by-step
approach to writing a simple iPhone (or iTouch) application, followed by a calculator application that enables you to use your iPhone to
perform simple arithmetic calculations with fractions.
Because object-oriented parlance involves a fair amount of terminology, Appendix A, "Glossary," provides definitions of some common
terms.
Appendix B, "Objective-C Language Summary," gives a summary of the Objective-C language, for your quick reference.
Appendix C, "Address Book Source Code," gives the source code listing for two classes that are developed and used extensively in Part
II of this text. These classes define address card and address book classes. Methods enable you to perform simple operations such as
adding and removing address cards from the address book, looking up someone, listing the contents of the address book, and so on.
After you've learned how to write Objective-C programs, you can go in several directions. You might want to lean more about the
underlying C programming language—or you might want to start writing Cocoa programs to run on Mac OS X, or develop more
sophisticated iPhone applications. In any case, Appendix D, "Resources," will guide you in the right direction.
Part I: The Objective-C 2.0 Language
1 Introduction
2 Programming in Objective-C
3 Classes, Objects, and Methods
4 Data Types and Expressions
5 Program Looping
6 Making Decisions
7 More on Classes
8 Inheritance
9 Polymorphism, Dynamic Typing, and Dynamic Binding
10 More on Variables and Data Types
11 Categories and Protocols
12 The Preprocessor
13 Underlying C Language Features
2. Programming in Objective-C
In this chapter, we dive right in and show you how to write your first Objective-C program. You won't work with objects just yet; that's
the topic of the next chapter. We want you to understand the steps involved in keying in a program and compiling and running it. We
give special attention to this process both under Windows and on a Macintosh computer.
To begin, let's pick a rather simple example: a program that displays the phrase "Programming is fun!" on your screen. Without further
ado, Program 2.1 shows an Objective-C program to accomplish this task:
Program 2.1.
// First program example
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSLog (@"Programming is fun!");
[pool drain];
return 0;
}
Compiling and Running Programs
Before we go into a detailed explanation of this program, we need to cover the steps involved in compiling and running it. You can both
compile and run your program using Xcode, or you can use the GNU Objective-C compiler in a Terminal window. Let's go through the
sequence of steps using both methods. Then you can decide how you want to work with your programs throughout the rest of this book.
Note
These tools should be preinstalled on all Macs that came with OS X. If you separately installed OS X, make sure you install the
Developer Tools as well.
Using Xcode
Xcode is a sophisticated application that enables you to easily type in, compile, debug, and execute programs. If you plan on doing
serious application development on the Mac, learning how to use this powerful tool is worthwhile. We just get you started here. Later we
return to Xcode and take you through the steps involved in developing a graphical application with it.
First, Xcode is located in the Developer folder inside a subfolder called Applications. Figure 2.1 shows its icon.