Aut lego vel scribo; doceo scrutorve sophian.
On June 2, 2014, Apple’s WWDC keynote address ended with a shocking announcement: “We have a new programming language.” This was surprising in several ways:
Having picked themselves up off the floor, developers immediately began to examine this new language — Swift — studying it, critiquing it, and deciding whether to adopt it. My own first move was to translate all my existing iOS apps into Swift; this was enough to convince me that, for all its faults, Swift deserved to be adopted by new students of iOS programming, and that my books, therefore, should henceforth assume that readers are using Swift.
Therefore, Swift is the programming language used throughout this book. Nevertheless, the reader will also need some awareness of Objective-C (including C). There are two chief reasons for this:
@dynamicin the Objective-C sense; in certain situations, Swift can be prohibitively slow in comparison to equivalent Objective-C code; and so on. Thus, I occasionally show some Objective-C code in this edition, in order to do things that Swift alone can’t accomplish.
Because Swift is new, I have had to settle on my own conventions for presenting and describing code. The most important question has been how to state the name of a method. My solution is to give the method’s Objective-C name. As an example, what is the name of the method that you call when you set a value using key–value coding? The actual call, in Swift, would be something like this:
But when I give the name of the method being called here, that name is
setValue:forKey:. This choice has several advantages:
Similarly, I will speak of the
setValue: parameter, even though, in an actual Swift method call, the name of that parameter appears before the parentheses, with no colon.
The grand exception to this rule is my treatment of initializers. Here, the difference between Objective-C and Swift is greater than a simple shorthand can readily encompass, so I give the initializer’s name as you would implement it. For example, in Objective-C, the default initializer for a UIView is
initWithFrame:. In this book, I will call that initializer
init(frame:). The same thing applies to what in Objective-C would be class factory methods with a corresponding initializer: when I want to mention what in Objective-C would be the UIImage class factory method
imageNamed:, I’ll call it
This treatment of initializer names has the great virtue that the name clarifies instantly that such a method is an initializer. Swift effectively abolishes class factory methods and brings such methods into the fold of formal initializers; my treatment of their names is a way of supporting and adopting that innovation.
Again, this convention requires some mental translation on the reader’s part, because in Swift the way you would name an initializer when you implement it is not the same as the way you would name it when you call it. If you were to override this method in a UIView subclass, you’d override
init(frame:); but if you were to call it to create a new UIView, you’d say
UIView(frame:). This mental translation, however, is hardly objectionable, as it is a practical fact to which every Swift user is already habituated.
So much for Swift. A new language is big news, but Swift is not the only big news connected with iOS 8. Nor is it the only welcome news. I’ve been arguing for years that Apple needs to check the rampant growth and evolution of the basic Cocoa Touch APIs and concentrate, for one release at least, on rationalizing the changes that have accumulated, often seemingly by random accretion, over the years. iOS 8 appears to do exactly that. To give just a couple of obvious examples:
Such rationalization permeates iOS 8, and I have eagerly adopted it, even where the prior approach is not yet deprecated. You could still create popovers and alerts the way we created them in iOS 7 and before; and obviously if you wanted your code to run on iOS 7 as well as iOS 8, you’d have to. But in this edition I behave, in effect, as if the old way didn’t exist. It’s the business of this edition to teach iOS 8, not to help you write backwards-compatible code; if you want to know how to deal with popovers (or anything else) in iOS 7 or before, consult an earlier edition of the book.
This book retains the structure of the previous edition. Like Homer’s Iliad, it begins in the middle of the story, with the reader jumping with all four feet into views and view controllers, and with a knowledge of the language and the Xcode IDE already presupposed. As in Programming iOS 7, discussion of the programming language, the Xcode IDE (including the nature of nibs, outlets, and actions, and the mechanics of nib loading), and the fundamental conventions, classes, and architectures of the Cocoa Touch framework (including delegation, the responder chain, key–value coding, memory management, and so on), has been expunged and relegated to a different book. This is material that constituted Chapters 1–13 of earlier editions, before Programming iOS 7, but whose presence was deemed to be making this book unwieldy in size and scope.
Here’s a summary of this book’s major sections:
delayfunction, which embraces
dispatch_afterwith a convenient shorthand; when I use
delayand you don’t know what it is, consult this appendix.
Someone who has read this book will, I believe, be capable of writing a real-life iOS app, and to do so with a clear understanding of what he or she is doing and where the app is going as it grows and develops. The book itself doesn’t show how to write any particularly interesting iOS apps (though it is backed by dozens of example projects that you can download from my GitHub site, http://github.com/mattneub/Programming-iOS-Book-Examples), but it does constantly use my own real apps and real programming situations to illustrate and motivate its explanations.
Just as important, this book is intended to prepare you for your own further explorations. In the case of some topics, especially in Parts III and IV, I guide you past the initial barrier of no knowledge into an understanding of the topic, its concepts, its capabilities, and its documentation, along with some code examples; but the topic itself may be so huge that there is room only to introduce it here. Your feet, nevertheless, will now be set firmly on the path, and you will know enough that you can now proceed further down that path on your own whenever the need or interest arises.
Indeed, there is always more to learn about iOS. iOS is vast! It is all too easy to find areas of iOS that have had to be ruled outside the scope of this book. In Part IV, for example, I peek at Core Data, and demonstrate its use in code, but a true study of Core Data would require an entire book of its own (and such books exist); so, having opened the door, I quickly close it again, lest this book suddenly double in size. By the same token, many areas of iOS are not treated at all in this book:
This book is geared to iOS 8.1 and Xcode 6.1, both of which became publicly available in October, 2014. In general, only very minimal attention is given to earlier versions of iOS and Xcode. As I’ve already said, it is not my intention to embrace in this book any detailed knowledge about earlier versions of the software, which is, after all, readily and compendiously available in my earlier books. The book does contain, nevertheless, a few words of advice about backward compatibility, and now and then I will call out a particularly noteworthy change from earlier system versions, especially where your existing iOS 7 code is likely to break or behave differently when compiled against iOS 8.
Xcode 6 has eliminated some of the templates that you choose from when creating a new project. The loss of the Utility Application template is a pity, because it embodied and illustrated the standard techniques for passing data to and from a presented view controller; but it hasn’t affected this book, because the template itself had become so ugly and crufty that in the previous edition I didn’t mention it in any case. The loss of the Empty Application template, on the other hand, is severe; it is, after all, perfectly reasonable to write an app without a storyboard (several of my own apps are structured in that way). Accordingly, near the start of the first chapter, I have given instructions for turning a Single View Application–based template into something similar to what the Empty Application template would have given you. Also, although I treat storyboards as the primary Interface Builder design milieu, I still do also assume that you know how to make and work with a .xib file when that is what you need or prefer.
At the time of this writing, Apple was still making frequent adjustments to the Swift language and to the way the Objective-C APIs are bridged to it. I have tried to keep my code up-to-date, but please make allowances, and be prepared to compensate, for the possibility that my examples may contain slight occasional impedance mismatches, such as the lack of a needed Optional unwrap or the presence of a superfluous one.
Screenshots of Xcode 6 were taken under OS X 10.9 Mavericks. At the time of writing, OS X 10.10 Yosemite was still in beta, and there’s no chance of my installing a beta of an operating system on my computer when I’m working on a mission-critical project. If you’re using Yosemite, your interface will naturally look slightly different from the screenshots.
My thanks go first and foremost to the people at O’Reilly Media who have made writing a book so delightfully easy: Rachel Roumeliotis, Sarah Schneider, Kristen Brown, Dan Fauxsmith, and Adam Witwer come particularly to mind. And let’s not forget my first and long-standing editor, Brian Jepson, who had nothing whatever to do with this edition, but whose influence is present throughout.
As in the past, I have been greatly aided by some fantastic software, whose excellences I have appreciated at every moment of the process of writing this book. I should like to mention, in particular:
The book was typed and edited entirely on my faithful Unicomp Model M keyboard (http://pckeyboard.com), without which I could never have done so much writing over so long a period so painlessly. For more about my physical work environment, see http://matt.neuburg.usesthis.com.
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 objects was severely and deliberately limited; on the other hand, the power and flexibility of some of those objects, especially such things as UITableView, was greatly enhanced over their 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.
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 OS X. Apple’s own annual WWDC developer conventions have reflected this trend, with their emphasis shifted from 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. 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 and elements on which sound iOS programming rests. 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 views before you know view controllers for the simple reason that Part I precedes Part II. 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 find 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.
The following typographical conventions are used in this book:
Constant width bold
Constant width italic
This element signifies a tip or suggestion.
This element signifies a general note.
This element indicates a warning or caution.
Supplemental material (code examples, exercises, etc.) is available for download at https://github.com/mattneub/Programming-iOS-Book-Examples.
This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Programming iOS 8 by Matt Neuburg (O’Reilly). Copyright 2015 Matt Neuburg, 978-1-491-90873-0.”
If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at email@example.com.
Technology professionals, software developers, web designers, and business and creative professionals use Safari Books Online as their primary resource for research, problem solving, learning, and certification training.
Members have access to thousands of books, training videos, and prepublication manuscripts in one fully searchable database from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technology, and hundreds more. For more information about Safari Books Online, please visit us online.
Please address comments and questions concerning this book to the publisher:
|O’Reilly Media, Inc.|
|1005 Gravenstein Highway North|
|Sebastopol, CA 95472|
|800-998-9938 (in the United States or Canada)|
|707-829-0515 (international or local)|
We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://bit.ly/programmingiOS8_5E.
To comment or ask technical questions about this book, send email to firstname.lastname@example.org.
For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia