As a courtesy, this is a full free rendering of my book, Programming iOS 6, by Matt Neuburg. Copyright 2013 Matt Neuburg. Please note that this book has now been completely superseded by two more recent books, iOS 7 Fundamentals and Programming iOS 7. If my work has been of help to you, please consider purchasing one or both of them. Thank you!

Preface

Aut lego vel scribo; doceo scrutorve sophian.

Sedulius Scottus

With the advent of version 2 of the iPhone system, Apple proved they could do a remarkable thing — adapt their existing Cocoa computer application programming framework to make applications for a touch-based device with limited memory and speed and a dauntingly tiny display. The resulting Cocoa Touch framework, in fact, turned out to be in many ways better than the original Cocoa.

A programming framework has a kind of personality, an overall flavor that provides an insight into the goals and mindset of those who created it. When I first encountered Cocoa Touch, my assessment of its personality was: “Wow, the people who wrote this are really clever!” On the one hand, the number of built-in interface widgets was severely and deliberately limited; on the other hand, the power and flexibility of some of those widgets, especially such things as UITableView, was greatly enhanced over their Mac OS X counterparts. Even more important, Apple created a particularly brilliant way (UIViewController) to help the programmer make entire blocks of interface come and go and supplant one another in a controlled, hierarchical manner, thus allowing that tiny iPhone display to unfold virtually into multiple interface worlds within a single app without the user becoming lost or confused.

Even more impressive, Apple took the opportunity to recreate and rationalize Cocoa from the ground up as Cocoa Touch. Cocoa itself is very old, having begun life as NeXTStep before Mac OS X even existed. It has grown by accretion and with a certain conservatism in order to maintain something like backward compatibility. With Cocoa Touch, on the other hand, Apple had the opportunity to throw out the baby with the bath water, and they seized this opportunity with both hands.

So, although Cocoa Touch is conceptually based on Mac OS X Cocoa, it is very clearly not Mac OS X Cocoa, nor is it limited or defined by Mac OS X Cocoa. It’s an independent creature, a leaner, meaner, smarter Cocoa. I could praise Cocoa Touch’s deliberate use of systematization (and its healthy respect for Occam’s Razor) through numerous examples. Where Mac OS X’s animation layers are glommed onto views as a kind of afterthought, a Cocoa Touch view always has an animation layer counterpart. Memory management policies, such as how top-level objects are managed when a nib loads, are simplified and clarified. And so on.

At the same time, Cocoa Touch is still a form of Cocoa. It still requires a knowledge of Objective-C. It is not a scripting language; it is certainly not aimed at nonprogrammers, like HyperCard’s HyperTalk or Apple’s AppleScript. It is still huge and complicated. In fact, it’s rather difficult.

The popularity of the iPhone, with its largely free or very inexpensive apps, and the subsequent popularity of the iPad, have brought and will continue to bring into the fold many new programmers who see programming for these devices as worthwhile and doable, even though they may not have felt the same way about Mac OS X. Apple’s own annual WWDC developer conventions have reflected this trend, with their emphasis shifted from Mac OS X to iOS instruction.

The widespread eagerness to program iOS, however, though delightful on the one hand, has also fostered a certain tendency to try to run without first learning to walk. iOS gives the programmer mighty powers that can seem as limitless as imagination itself, but it also has fundamentals. I often see questions online from programmers who are evidently deep into the creation of some interesting app, but who are stymied in a way that reveals quite clearly that they are unfamiliar with the basics of the very world in which they are so happily cavorting.

It is this state of affairs that has motivated me to write this book, which is intended to ground the reader in the fundamentals of iOS. I love Cocoa and have long wished to write about it, but it is iOS and its popularity that has given me a proximate excuse to do so. Indeed, my working title was “Fundamentals of Cocoa Touch Programming.” Here I have attempted to marshal and expound, in what I hope is a pedagogically helpful and instructive yet ruthlessly Euclidean and logical order, the principles on which sound iOS programming rests, including a good basic knowledge of Objective-C (starting with C itself) and the nature of object-oriented programming, advice on the use of the tools, the full story on how Cocoa objects are instantiated, referred to, put in communication with one another, and managed over their lifetimes, and a survey of the primary interface widgets and other common tasks. My hope, as with my previous books, is that you will both read this book cover to cover (learning something new often enough to keep you turning the pages) and keep it by you as a handy reference.

This book is not intended to disparage Apple’s own documentation and example projects. They are wonderful resources and have become more wonderful as time goes on. I have depended heavily on them in the preparation of this book. But I also find that they don’t fulfill the same function as a reasoned, ordered presentation of the facts. The online documentation must make assumptions as to how much you already know; it can’t guarantee that you’ll approach it in a given order. And online documentation is more suitable to reference than to instruction. A fully written example, no matter how well commented, is difficult to follow; it demonstrates, but it does not teach.

A book, on the other hand, has numbered chapters and sequential pages; I can assume you know C before you know Objective-C for the simple reason that Chapter 1 precedes Chapter 2. And along with facts, I also bring to the table a degree of experience, which I try to communicate to you. Throughout this book you’ll see me referring to “common beginner mistakes”; in most cases, these are mistakes that I have made myself, in addition to seeing others make them. I try to tell you what the pitfalls are because I assume that, in the course of things, you will otherwise fall into them just as naturally as I did as I was learning. You’ll also see me construct many examples piece by piece or extract and explain just one tiny portion of a larger app. It is not a massive finished program that teaches programming, but an exposition of the thought process that developed that program. It is this thought process, more than anything else, that I hope you will gain from reading this book.

iOS is huge, massive, immense. It’s far too big to be encompassed in a book even of this size. And in any case, that would be inappropriate and unnecessary. There are entire areas of Cocoa Touch that I have ruthlessly avoided discussing. Some of them would require an entire book of their own. Others you can pick up well enough, when the time comes, from the documentation. This book is only a beginning — the fundamentals. But I hope that it will be the firm foundation that will make it easier for you to tackle whatever lies beyond, in your own fun and rewarding iOS programming future.

Acknowledgments for the First Edition

It’s a poor craftsman who blames his tools. No blame attaches to the really great tools by which I have been assisted in the writing of this book. I am particularly grateful to the Unicomp Model M keyboard (http://pckeyboard.com), without which I could not have produced so large a book so painlessly. I was also aided by wonderful software, including TextMate (http://macromates.com) and AsciiDoc (http://www.methods.co.nz/asciidoc). BBEdit (http://www.barebones.com) helped with its diff display. Screenshots were created with Snapz Pro X (http://www.ambrosiasw.com) and GraphicConverter (http://www.lemkesoft.com); diagrams were drawn with OmniGraffle (http://www.omnigroup.com).

The splendid O’Reilly production process converted my AsciiDoc text files into PDF while I worked, allowing me to proofread in simulated book format. Were it not for this, and the Early Release program that permitted me to provide my readers with periodic updates of the book as it grew, I would never have agreed to undertake this project in the first place. I would like particularly to thank Tools maven Abby Fox for her constant assistance.

I have taken advice from two tech reviewers, Dave Smith and David Rowland, and have been assisted materially and spiritually by many readers who submitted errata and encouragement. I was particularly fortunate in having Brian Jepson as editor; he provided enthusiasm for the O’Reilly tools and the electronic book formats, a watchful eye, and a trusting attitude; he also endured the role of communications pipeline when I needed to prod various parts of the O’Reilly machine. I have never written an O’Reilly book without the help of Nancy Kotary, and I didn’t intend to start now; her sharp eye has smoothed the bristles of my punctuation-laden style. For errors that remain, I take responsibility, of course.

Notes on the Second Printing

For the second printing of this book, screenshots have been rendered more legible, and a major technical error in the presentation of key–value coding in Chapter 5 has been corrected. In addition, numerous small emendations have been made; many of these have resulted from errata submissions by my readers, whom I should like to thank once again for their continued assistance and kind support. Please note that these changes have altered the pagination of the printed and PDF editions of the book.

Acknowledgments for the Second Edition

Not surprisingly, I’d like to thank once again my editor, Brian Jepson, who made me write this new edition. You can put down the whip now, Brian. Thanks also to the O’Reilly team for their many-faceted assistance, and always to my readers for their enthusiasm, encouragement, loyalty, and suggestions.

Notes on the Second Edition

In order to describe the relationship of the second edition of this book with the first edition, it will help if I first recap the recent history of iOS and Xcode versions.

At the time I started writing the first edition this book, system versions 3.1.3 (on the iPhone) and 3.2 (on the iPad) were current. As I was working on the book, iOS 4 and the iPhone 4 came into being, but iOS 4 didn’t yet run on the iPad. Subsequently iOS 4.2 emerged; this was the first system able to run on both the iPhone and the iPad. At the same time, Xcode was improved up to 3.2.5. iOS 4 was the first version of the system to support multitasking, which necessitated much scurrying about on the part of developers, to adapt their apps to the new world order.

Just in time for my final revisions of the first edition, Xcode 3.2.6 and iOS 4.3 were released, along with the first public version of the long-awaited Xcode 4. Xcode 4 was a thorough overhaul of the IDE: menus, windows, and preferences are quite different from Xcode 3.2.x. Both Xcode 4 and Xcode 3.2.x can coexist on the same machine (up through Snow Leopard) and can be used to work on the same project; moreover, Xcode 3.2.x has some specialized capabilities that Xcode 4 lacks, so some long-standing developers may well continue to use it. This situation presents a dilemma for an author describing the development process. However, for iOS programming, I recommend adoption of Xcode 4, and the first edition of this book assumed that the reader had adopted it.

Such was the situation in May 2011, when the first edition was formally released, describing how to program iOS 4.

Less than five months later, in October 2011, Apple released iOS 5. Some of the features that are new in iOS 5 are dramatic and pervasive, and it is this fact which has necessitated a full revision of this book. At the same time, Apple also released Xcode 4.2, and this book assumes that you are using that version of Xcode (or later), since it is the earliest version of Xcode on which iOS 5 development is officially possible. (It may be that, by deep trickery, one can develop for iOS 5 using an earlier version of Xcode, but that would constitute unsupported behavior.) The first edition had a few mentions of menu commands and other interface in Xcode 3.2.x, but they have been excised from this edition. Xcode 4.2 comes in two flavors, depending whether you’re running Snow Leopard (Mac OS X 10.6) or Lion (Mac OS X 10.7) on your development machine; they are supposed to behave more or less identically, but in fact each has its own bugs, so feel free to try both.

As I was finishing the second edition, in February 2012, Xcode 4.3 was released (for Lion only). Its chief innovation has to do with the organization of files on disk: instead of arriving as an installer that creates a top-level Developer folder to hold its many ancillary files and folders, Xcode 4.3 contains the Developer folder inside its file package (you can see it with the Finder’s Show Package Contents command). So when I speak of the Developer folder in this book, you would need to understand that I mean something like /Applications/Xcode.app/Contents/Developer. I have not found any other major differences between Xcode 4.2 and Xcode 4.3, and in this book I will sometimes say “Xcode 4.2” to mean Xcode 4.2 or later.

The chief purpose of this new edition, then, is to bring the book up to date for iOS 5. You, the reader, might be coming to iOS programming for the first time, so this edition assumes no prior knowledge of iOS 4 or any previous version. On the other hand, you, like me, could be making the transition from iOS 4 to iOS 5, so this edition lays some special emphasis on features that are new in iOS 5. This emphasis could also be useful to new iOS programmers who are thinking of writing apps that can also run under iOS 4. My goal, however, is not to burden the reader with outdated information. The vast majority of devices that could run iOS 4 have probably been updated to iOS 5, and you will probably be right in assuming that there will plenty of iOS 5 users out there, without your having to bother to target earlier systems. And from a pedagogical point of view, it seems counterproductive to describe how things used to be — especially as, if you’re really interested, you can always consult the previous edition of this book! For this reason, some references to the state of things before iOS 4.2 have been excised from this edition.

Here is a case in point, showing my attitude and pedagogical approach with regard to new iOS 5 features in this edition. iOS 5 introduces ARC (automatic reference counting), which changes the way in which Objective-C programmers manage object memory so profoundly as to render Objective-C a different language. Use of ARC is optional in programming iOS, but it is extraordinarily helpful to have it turned on, and in this book I therefore assume throughout that you do have it turned on. In Chapter 12, where I discuss memory management, I still describe what life is like without ARC, as I did in the previous edition; but, outside that chapter, all code examples, unless specifically stated otherwise, are supposed to be running under ARC. If you start a new Xcode project with File → New Project and pick any iOS application template, then if “Use Automatic Reference Counting” is checked in the second screen, you’re using ARC.

iOS 5 also introduces storyboards. A storyboard file is similar to a nib file: it’s a place where Xcode lets you “draw” parts of the interface. The main difference is that a single storyboard file can do the work of multiple nib files. Nib files and storyboard files are not identical, nor are they used identically, but because of their similarity, when I speak of a nib file generically, in this book, I mean a nib or storyboard file, indifferently. I’ll try to indicate this at the time, but the reader will forgive me if I don’t keep saying “nib or storyboard” all the time.

In closing, I should like to say a few words to the people who have, in my opinion, gratuitously criticized the previous edition of this book on one or more of the following grounds:

  1. It isn’t a “cookbook” (a book full of step-by-step instructions for creating full working applications).
  2. It devotes hundreds of pages to fundamentals.
  3. It doesn’t get the reader started early on with hands-on programming; there isn’t even a “Hello, World” tutorial.

All of that is perfectly true. It is also quite deliberate. As both the table of contents and this preface are at pains to make clear, this is not that type of book. To paraphrase Butler’s Law, this book is the type of book it is, and not some other type. That’s why I wrote this book in the first place. The books of the type that these critics seem to want this book to be exist by the score; books of the type that this book is, however, seemed to me not to exist at all. As with all my other books, so with this one: when I couldn’t find the book I wanted, I wrote it myself. I expect this book to be useful to those who need this type of book. People who prefer some other type of book should get some other type of book, and not mar my book’s web page by criticizing it for not being what it was never intended to be.

The purpose of this book is to proceed by focusing on the underlying knowledge needed for an actual understanding of iOS programming. That is precisely the opposite of a cookbook. This book has no simple recipes ready for you to drop into your own code and come up with an app. I don’t give you some fish; I teach you what a fish is and what you need to know to obtain one. The number of books out there that skip blithely past the fundamentals, leaving the reader to pick up Objective-C somehow independently, is painfully huge. The result is that numerous learners are encouraged to try their hand at programming when, to judge from the nature of the questions they ask and the confusion they exhibit, they don’t understand what they are doing.

This book acts as a corrective, which in turn requires that space be devoted to fundamentals. The book does not hold a gun to your head and force you to read all about all of those fundamentals; if you already know everything there is to know about C, about Objective-C, about Xcode, about Cocoa, about views and drawing or whatever (but do you? do you really?), then by all means, skip those opening chapters. But don’t begrudge to the people who need them the explanations that this book contains, as those are the people at whom they are aimed.

That explains why there’s no attempt, in this book, to rush the reader into hands-on programming. My book does not pander to a desire for the false, cheap gratification of making believe that one is a programmer merely because one can parrot some instructions. My book is about knowledge — hard-won, rigorously gained knowledge. It’s about gaining an understanding of what you are doing when you program iOS 5. It calls for a substantial investment of time and thought, and many pages elapse before any practical programming is demonstrated.

Perhaps part of the misunderstanding here is that the critic has not noticed, or has not understood, the sentence earlier in this Preface stating that my book is written in “a pedagogically helpful and instructive yet ruthlessly Euclidean and logical order.” Some people may not know or appreciate what “Euclidean” means. It means “in the manner of Euclid.” Euclid wrote our first surviving mathematical textbook, and it is distinguished by the following remarkable characteristic, among others: if concept or assertion B depends upon concept or assertion A, A comes first. Nothing is postponed; Euclid never says, “I’ll explain/prove/discuss this point later, but for now, just take my word for it.” I have attempted to copy Euclid’s model. So, to take an obvious example, all real iOS apps use view controllers. It’s true, then, that the reader isn’t told what’s involved in constructing a real iOS app until Chapter 19 is reached and view controllers are discussed. But to understand view controllers, you need to know what’s being controlled, namely, a view; hence Chapter 14 and the rest of Part IV. Views. And to grasp the relationship between a view controller and its view, you need to know about Cocoa’s architectural patterns, such as lifetime events and the responder chain; hence Chapter 11 and the rest of Part III. Cocoa. Moreover, a view controller’s view is often loaded from a nib; hence Chapter 7. And all of that requires a knowledge of the programming language you’ll be using, Objective-C; hence Chapter 3. But Objective-C is C; hence Chapter 1. So to reach view controllers any sooner would have been impossible. I rest my case.

Anyway, the complaint that the reader of my book doesn’t get to run any code is factually false. The book is crammed full of substantial code examples — all of which are available for download from my GitHub site (https://github.com/mattneub), so you can obtain them, run them in Xcode, and play with them to your heart’s content. So you can and should, in fact, be running code right from the outset. Nevertheless, the purpose of the code in this book is not for the fun of running it. All of my code is to support your understanding of whatever concepts I’m explaining at that point in the book.

In any case, perfectly good hands-on “Hello, World” tutorials are a dime a dozen; they’re plastered all over the Internet, including at Apple’s own site (http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhone101/Articles/). You don’t need me to show you that the process of writing a trivial iPhone application is fun and easy.

Still, for those who feel strongly that I haven’t done my job unless I supply a “Hello, World” example, here is one, complete with step-by-step instructions:

  1. Install Xcode, and launch the Xcode application.
  2. Choose File → New → Project.
  3. In the “Choose a template” dialog, under “iOS” on the left (not “Mac OS X”), click Application. On the right, click Empty Application. Click Next.
  4. For Product Name, type Hello. Enter a company identifier if there isn’t one already, such as com.yourLastName.yourFirstName. Choose Device Family: iPhone. Uncheck all three checkboxes. Click Next.
  5. Navigate to the Desktop. Uncheck “Create local git repository.” Click Create.
  6. The project window opens. Press Command-1. At the left, click AppDelegate.m.
  7. Work in the editor in the middle of the window. Look for the words “Override point for customization after application launch.” Place the cursor to the right of those words and hit Return a few times, to make some white space. Click in that white space and type these lines of code:

    UILabel* label = [[UILabel alloc] init];
    label.text = @"Hello, world!";
    [label sizeToFit];
    CGRect f = label.frame;
    f.origin = CGPointMake(100,100);
    label.frame = f;
    [self.window addSubview:label];
  8. Press Command-R. If you see a dialog asking whether you want to save, accept.
  9. After a while, the iOS Simulator application appears, containing a white window with “Hello, world!” in it.

Congratulations. You’ve made a “Hello, world” example. Wasn’t that easy? Wasn’t it boring? Wasn’t it pointless? And are you any the wiser as to what, in fact, you just did? To find out — and, even more important, to know enough to be able to progress further on your own — read this book.

Acknowledgments for the Third Edition

This edition was written in the full public gaze, and I’d like to thank, as always, my many sharp-eyed readers who assisted me by spotting mistakes and making suggestions. I would also like to say a word for wonderful, wonderful git (http://git-scm.com), as well as the extraordinary SourceTree (http://www.sourcetreeapp.com).

At O’Reilly Media, I am grateful to XSL and CSS wizard Sarah Schneider, who brilliantly and quickly tweaked the automated layout process to make this book look great in printed and PDF form.

Notes on the Third Edition

Shortly after the official release of iOS 6 and Xcode 4.5, I began revising the code examples in this book (available at https://github.com/mattneub) to use and demonstrate the new iOS features. When that was done, I proceeded to rewrite the book text; while I was doing so, iOS 6.1 and Xcode 4.6 were released, so those are the versions that the book now assumes you’re using.

For this third edition, I have eliminated most references to previous iOS versions. Many iOS 6 features, of course, do not exist in iOS 5 or before; I usually mention that a new feature is new, but I have not generally addressed the problem of writing backwards-compatible code. The text would become confusing and bloated if everything had to be qualified with advice for different versions (“but if you’re targeting iOS 5.1, do this; if you’re targeting iOS 5.0, do that; if you’re targeting iOS 4.3, do the other”). I believe I can justify such omission on the grounds that the previous editions of this book exist! If you’re targeting iOS 5, I’ve already described what to do, in the second edition; there’s no need to repeat myself here.

New iOS 6 features are, of course, both explained and adopted in this edition. For example, having described NSArray subscripting (in Chapter 10), I then use it consistently, in place of objectAtIndex:, throughout the rest of the book. Aside from this, the book’s structure remains the same as in previous editions, growing where necessary to accommodate explanations of new features, such as autolayout (in Chapter 14), state restoration (in Chapter 19), and collection views (in Chapter 21). Also, in response to reader requests, I have inserted a short example of Core Data programming into Chapter 36.