A few months ago, Pearson Education contacted me about writing a book about Cocoa Touch. I agreed because although I had a lot of experience on other platforms, I found Cocoa somewhat bewildering when I first encountered it. Most books either assumed a Mac background or really wanted to teach me Object-Oriented programming from the ground up. Often after reading one of them, I had the impression I had learnt something until I tried to apply whatever it was I learned: The problem was that they glossed over how Cocoa really works, and why it was architected in that way.
Cocoa and Objective-C are very powerful tools to build Applications and Graphical Interfaces quickly. This power comes from splitting GUI tasks into a few well-chosen abstractions that reduce the amount of code we have to write. Once understood, these abstractions seem obvious, so most books simply introduce them as the way things are done in Cocoa, leaving beginners bewildered.
Instead I show readers how these abstractions work and how they simplify their code. Because they understand the mechanics of each task, readers will be able to resolve most difficulties on their own quickly, rather than exploring new levels of frustration. To further help, the book is interlaced with debugging techniques. My goal in writing the book was to provide a sound foundation that programmers can use to build functional applications, and feel confident that they can solve the problems they will encounter. Instead of covering the latest API fashions, I concentrate on the APIs and tools you’ll actually use and will need to understand.
The book was published last Thursday, Oct 15 2009, and is available now at the publisher’s. Amazon shows they have yet to receive it (and therefore discount it). It’s in full color!
Understanding the Objective-C Language
In the first five chapters, you’ll build a basic application: a Calculator. You’ll learn how to use the key tools used when developing iPhone applications: Xcode, the debugger and Interface Builder. It also teaches you Objective-C: Objective-C is a thin layer on top of C which adds language support for object-oriented programming. Cocoa uses reference counting for memory management, but the judicious use of auto release pools makes this much easier than you might expect. You’ll also learn about Cocoa Touch’s Foundation classes with provide basic functionality such as Unicode strings, arrays, dictionaries. Practically speaking, by the end of chapter 4 you’ll have written a functioning calculator.
When I first learned Objective-C, I found many bugs intractable because I did not understanding messaging. To help you avoid this pitfall, I explain messaging and how it is implemented in chapter 4. Similarly, it took a while for me to understand auto release pools. They simplify your code, but are often presented as a form of magic you just use. My book is a magic-free zone, clarifying how they work and their limitations up-front. Other Objective-C particularities you’ll learn about are class objects, updating classes on the fly, class clusters, key-value coding and key-value observing. By the end of chapter 5, for most intents and purposes you’ll be an Objective-C expert. Unlike competing books, and Apple’s own documentation, I detail the computational complexity of Objective-C arrays and dictionaries.
User Interface Foundations
The building blocks of user interfaces are views. To build a user interface from views, one simply builds a tree of views (a view hierarchy) which specifies the location and order in which views are drawn. Most interfaces can be built using Interface Builder, a graphical design tool. Unlike competing solutions, Interface Builder does not generate code, but a NIB file that states how to build the view hierarchy. Most books only cover building user interfaces in Interface Builder. As a programmer this left me with a bad taste, as I was relying on some unknown mechanism working behind my back. Debugging was difficult because I had no idea how NIB files were loaded. Instead I show you how to build view hierarchies in code, how NIB files are loaded, and the pitfalls you may encounter.
Views draw themselves using a 2D renderer called Core Graphics (or Quartz). They respond to user interaction dispatched to them by Cocoa. Implementing your own User Interface element (a button) will give you a clear understanding of the ins and outs of user interface elements, and will help you polish your applications with custom user interface elements.
Unlike most user-interface solutions, Cocoa is not architected as a library. That is to say, your application does not just call library functions at will. Cocoa is architected as a framework: it calls your application code when it needs to. This turns out to be a powerful solution, but is disconcerting for programmers coming from other platforms. Because misunderstanding the run loop causes seemingly unrelated bugs I spend entire chapter discussing how run loop is used and how it interacts with other Cocoa sub-systems such as the auto release pool, and the responder chain.
A distinguishing feature of the iPhone’s user interface is how much animation it uses. These animations are created with Core Animation. Core Animation uses the iPhone’s 3D graphics chip and a separate thread to create smooth animations. Understanding Core Animation’s architecture will help you use it and remember its limitations. To further help you I share tips learned developing commercial software. By the end of this chapter, you’ll have implemented your own Cover Flow clone shown above! (animal images courtesy of http://www.public-domain-image.com).
Advanced User-Interface Elements
View Controllers reduce the amount of code you must write. Unlike many beginning programmers, you will not confuse them with views because the book clearly differentiates them. An example will solidify your understanding: displaying a Scientific Mode in the calculator when the iPod is rotated.
Tables are an essential component of most user interfaces. The iPhone’s table support is particularly flexible, and I’ll show you how you can customize it to create fast scrolling distinctive tables. In this hour, you’ll build a table based application that lazily loads data from an Internet source: a Twitter application.
Many applications present information on multiple screens. Navigation bars and Tab bars provide a standard way of navigating between the screens. I show you how to build applications using these user interface elements, and show you how the views and view controllers interact.
iPhone OS 3.0 introduces undo/redo functionality. Cocoa Touch solves this problem in a particularly elegant manner. However, it differs substantially from other solutions you may have used. To help you understand it fully, I dedicate an entire chapter to understanding the problems it solves, how it works, and why it was architected in this way.
Accessing the Internet
By providing full internet connectivity and the ability to render most web pages, the iPhone enables whole new classes of applications. To help you build robust applications, chapter 14 discusses how networks work in detail. Working through a real example (adding error handling to the Twitter application) shows you how this is done in practice.
Saving and Retrieving Data
Cocoa Touch provides four means of saving and retrieving data: application preferences, files, a small sql database, and Core Data. You’ll learn how to add application preferences to the Twitter application, that users can customize in the Settings application. In chapter 17, I discuss when and how to use files or the sqlite database. iPhone OS 3.0 added Core Data which lets you load and save objects to storage transparently by providing a single object definition instead of writing your own classes and your own serialization code. To help you decide whether or not to use Core Data, I discuss its performance characteristics.
Interacting with the World
Only a few years ago, the idea of a tiny device containing your music and video library, finding your location anywhere on the planet, and using accelerometers as a user interface would have seemed like Science Fiction. The iPhone is a remarkable convergence device. Chapters 19 and 20 explains how to use these capabilities in detail.
Chapter 21 shows you how to share data with other applications. Custom URLs let you start other applications. Pasteboards provide cross-application copy and paste functionality. To export data from your device, I show you how to send emails from your application, or run a tiny webserver.
Completing Your Application
Completing your application involves four tasks: debugging it, optimizing it, localizing it and shipping it.
I devote an entire chapter to debugging, showing you not only how to use the debugger gdb, but also dtrace, valgrind, and nib2obj. Sometimes however, bugs are caused by misunderstanding how the frameworks work. Usually other programmers can help you, but sometimes the only solution is to reverse engineer the framework. To help you do this, the chapter ends with a short tutorial teaching you how to do this.
Optimizing your application is another key topic and has its own chapter. You’ll learn how to write your own profiling code, and learn how to use the two iPhone profilers: Shark and Instruments. Because of the iPhone’s memory limitations, it is particularly important to minimize your application’s memory consumption. To further help you, I introduce the Clang static analysis tool which helps you detect memory leaks at compilation time.
The final chapter covers localization and shipping your application. Because the App Store is the only authorized means of distributing applications, and because Apple can reject your application once you submit it for publication, developing for the iPhone is somewhat risky. To help you mitigate this risk, I analyze the types of applications Apple has refused to distribute on the AppStore, and provide some simple guidelines to follow.
If you haven’t programmed C in a while, I provide Appendix A to quickly refresh your memory of the salient points.
While developing for the iPhone you may encounter a number of issues due to Apple’s development tools. To help you resolve these issues quickly, Appendix B devotes 18 pages to debugging these issues.
Appendix C lists resources I have found useful when developing iPhone applications.
Appendix D includes a number of advanced topics of interest to expert programmers: how Cocoa starts your application, a deeper discussion of exceptions, and how and when to use threads.