Tải bản đầy đủ (.pdf) (1,014 trang)

oreilly programming ios 5, fundamentals of iphone ipad ipod touch development 2nd (2012)

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (16.66 MB, 1,014 trang )

SECOND EDITION
Programming iOS 5
Matt Neuburg
Beijing

Cambridge

Farnham

Köln

Sebastopol

Tokyo
Programming iOS 5, Second Edition
by Matt Neuburg
Copyright © 2012 Matt Neuburg. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions
are also available for most titles (). For more information, contact our
corporate/institutional sales department: (800) 998-9938 or
Editor: Brian Jepson
Production Editor: Kristen Borg
Proofreader: O’Reilly Production Services
Indexer: Matt Neuburg
Cover Designer: Karen Montgomery
Interior Designer: David Futato
Illustrator: Matt Neuburg


March 2012: Second Edition.
Revision History for the Second Edition:
2011-12-23 Early release
2012-03-12 First release
See for release details.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of
O’Reilly Media, Inc. Programming iOS 5, the image of a kingbird, and related trade dress are trademarks
of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a
trademark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and author assume
no responsibility for errors or omissions, or for damages resulting from the use of the information con-
tained herein.
ISBN: 978-1-449-31934-2
[M]
1331571373
Table of Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
Part I. Language
1. Just Enough C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Compilation, Statements, and Comments 4
Variable Declaration, Initialization, and Data Types 6
Structs 8
Pointers 10
Arrays 13
Operators 14
Flow Control and Conditions 16
Functions 20
Pointer Parameters and the Address Operator 23

Files 25
The Standard Library 27
More Preprocessor Directives 28
Data Type Qualifiers 29
2. Object-Based Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Objects 31
Messages and Methods 32
Classes and Instances 33
Class Methods 36
Instance Variables 37
The Object-Based Philosophy 38
3. Objective-C Objects and Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
An Instance Reference Is a Pointer 43
Instance References, Initialization, and nil 44
iii
Instance References and Assignment 47
Instance References and Memory Management 49
Messages and Methods 49
Sending a Message 50
Declaring a Method 51
Nesting Method Calls 52
No Overloading 53
Parameter Lists 53
Unrecognized Selectors 54
Typecasting and the id Type 56
Messages as Data Type 59
C Functions 60
CFTypeRefs 62
Blocks 63
4. Objective-C Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

Class and Superclass 67
Interface and Implementation 69
Header File and Implementation File 71
Class Methods 73
The Secret Life of Classes 74
5. Objective-C Instances . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
How Instances Are Created 77
Ready-Made Instances 77
Instantiation from Scratch 78
Nib-Based Instantiation 81
Polymorphism 82
The Keyword self 84
The Keyword super 86
Instance Variables and Accessors 89
Key–Value Coding 91
Properties 91
How to Write an Initializer 94
Part II. IDE
6. Anatomy of an Xcode Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
New Project 100
The Project Window 101
The Navigator Pane 103
The Utilities Pane 107
iv | Table of Contents
The Editor 109
The Project File and Its Dependents 111
The Target 114
Build Phases 114
Build Settings 115
Configurations 117

Schemes and Destinations 118
From Project to App 120
Build Settings 122
Property List Settings 122
Nib Files and Storyboard Files 123
Other Resources 124
Code 126
Frameworks and SDKs 128
7. Nib Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
A Tour of the Nib-Editing Interface 134
The Dock 135
Canvas 136
Inspectors and Libraries 138
Nib Loading and File’s Owner 140
Making and Loading a Nib 142
Outlet Connections 143
More Ways to Create Outlets 148
More About Outlets 150
Action Connections 151
Additional Initialization of Nib-Based Instances 155
8. Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
The Documentation Window 158
Class Documentation Pages 159
Sample Code 163
Other Resources 164
Quick Help 164
Symbols 165
Header Files 165
Internet Resources 166
9. Life Cycle of a Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169

Choosing a Device Architecture 169
Localization 173
Editing Your Code 174
Autocompletion 175
Table of Contents | v
Snippets 176
Live Syntax Checking and Fix-it 177
Navigating Your Code 177
Debugging 180
Caveman Debugging 180
The Xcode Debugger 183
Unit Testing 188
Static Analyzer 189
Clean 189
Running in the Simulator 190
Running on a Device 192
Device Management 196
Version Control 196
Instruments 198
Distribution 202
Ad Hoc Distribution 204
Final App Preparations 206
Icons in the App 206
Other Icons 207
Launch Images 208
Screenshots 209
Property List Settings 209
Submission to the App Store 211
Part III. Cocoa
10. Cocoa Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217

Subclassing 217
Categories 220
Splitting a Class 221
Private Method Declarations 222
Protocols 223
Optional Methods 227
Some Foundation Classes 229
Useful Structs and Constants 229
NSString and Friends 230
NSDate and Friends 232
NSNumber 232
NSValue 233
NSData 233
Equality and Comparison 234
NSIndexSet 234
vi | Table of Contents
NSArray and NSMutableArray 235
NSSet and Friends 236
NSDictionary and NSMutableDictionary 237
NSNull 239
Immutable and Mutable 239
Property Lists 240
The Secret Life of NSObject 240
11. Cocoa Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
Reasons for Events 246
Subclassing 246
Notifications 248
Receiving a Built-In Notification 249
Unregistering 251
NSTimer 253

Delegation 253
Data Sources 257
Actions 258
The Responder Chain 263
Deferring Responsibility 264
Nil-Targeted Actions 264
Application Lifetime Events 265
Swamped by Events 270
12. Accessors and Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
Accessors 275
Key–Value Coding 277
Memory Management 281
Principles of Cocoa Memory Management 281
The Golden Rules of Memory Management 282
What ARC Is and What It Does 285
How Cocoa Objects Manage Memory 288
Autorelease 290
Memory Management of Instance Variables (Non-ARC) 293
Memory Management of Instance Variables (ARC) 297
Retain Cycles and Weak References 299
Nib Loading and Memory Management 306
Memory Management of Global Variables 307
Memory Management of Pointer-to-Void Context Info 308
Memory Management of CFTypeRefs 310
Properties 313
Table of Contents | vii
13. Data Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
Model–View–Controller 319
Instance Visibility 321
Visibility by Instantiation 322

Visibility by Relationship 323
Global Visibility 324
Notifications 325
Key–Value Observing 327
Part IV. Views
14.
Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
The Window 335
Subview and Superview 338
Frame 341
Bounds and Center 343
Layout 346
Transform 349
Visibility and Opacity 353
15. Drawing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
UIImage and UIImageView 355
Graphics Contexts 359
UIImage Drawing 363
CGImage Drawing 364
CIFilter and CIImage 367
Drawing a UIView 370
Graphics Context Settings 372
Paths and Drawing 373
Clipping 377
Gradients 378
Colors and Patterns 380
Graphics Context Transforms 382
Shadows 384
Points and Pixels 385
Content Mode 385

16. Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
View and Layer 390
Layers and Sublayers 392
Manipulating the Layer Hierarchy 393
Positioning a Sublayer 394
viii | Table of Contents
CAScrollLayer 395
Layout of Sublayers 396
Drawing in a Layer 396
Content Resizing and Positioning 399
Layers that Draw Themselves 401
Transforms 403
Depth 406
Shadows, Borders, and More 409
Layers and Key–Value Coding 411
17.
Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
Drawing, Animation, and Threading 414
UIImageView and UIImage Animation 417
View Animation 419
Animation Blocks 419
Modifying an Animation Block 420
Transition Animations 424
Block-Based View Animation 425
Implicit Layer Animation 430
Animation Transactions 431
Media Timing Functions 432
Core Animation 434
CABasicAnimation and Its Inheritance 434
Using a CABasicAnimation 436

Keyframe Animation 439
Making a Property Animatable 440
Grouped Animations 441
Transitions 445
The Animations List 447
Actions 449
What an Action Is 449
The Action Search 450
Hooking Into the Action Search 451
Nonproperty Actions 454
Emitter Layers 455
18. Touches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
Touch Events and Views 464
Receiving Touches 466
Restricting Touches 467
Interpreting Touches 468
Gesture Recognizers 473
Gesture Recognizer Classes 473
Table of Contents | ix
Multiple Gesture Recognizers 477
Subclassing Gesture Recognizers 479
Gesture Recognizer Delegate 481
Touch Delivery 483
Hit-Testing 484
Initial Touch Event Delivery 489
Gesture Recognizer and View 490
Touch Exclusion Logic 491
Recognition 492
Touches and the Responder Chain 493
Part V. Interface

19. View Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
The View Controller Hierarchy 500
View Controller and View Creation 504
Manual View 507
Generic Automatic View 509
View in a Separate Nib 511
Nib-Instantiated View Controller 514
Storyboard-Instantiated View Controller 517
Rotation 519
Rotation Events 521
Initial Orientation 523
Presented View Controller 526
Presented View Animation 531
Presentation Styles 532
Presented Views and Rotation 534
Tab Bar Controllers 536
Tab Bar Items 537
Configuring a Tab Bar Controller 538
Navigation Controllers 540
Bar Button Items 544
Navigation Items 546
Toolbar Items 549
Configuring a Navigation Controller 549
Page View Controller 551
Container View Controllers 554
Storyboards 557
View Controller Lifetime Events 562
View Controller Memory Management 564
x | Table of Contents
20. Scroll Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569

Creating a Scroll View 570
Scrolling 573
Paging 576
Tiling 577
Zooming 579
Zooming Programmatically 581
Zooming with Detail 581
Scroll View Delegate 584
Scroll View Touches 586
Scroll View Performance 591
21. Table Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593
Table View Cells 596
Built-In Cell Styles 597
Custom Cells 603
Table View Data 611
The Three Big Questions 612
Table View Sections 616
Refreshing Table View Data 619
Variable Row Heights 621
Table View Selection 623
Table View Scrolling and Layout 629
Table View Searching 630
Table View Editing 636
Deleting Table Items 639
Editable Content in Table Items 640
Inserting Table Items 642
Rearranging Table Items 644
Dynamic Table Content 645
Table View Menus 646
22. Popovers and Split Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649

Configuring and Displaying a Popover 651
Managing a Popover 656
Dismissing a Popover 657
Popover Segues 660
Automatic Popovers 661
Split Views 663
23. Text .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671
UILabel 672
UITextField 673
Table of Contents | xi
Editing and the Keyboard 676
Configuring the Keyboard 680
Text Field Delegate and Control Event Messages 681
The Text Field Menu 683
UITextView 685
Core Text 688
24. Web Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697
Loading Content 698
Communicating with a Web View 704
25. Controls and Other Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 707
UIActivityIndicatorView 707
UIProgressView 708
UIPickerView 711
UISearchBar 713
UIControl 716
UISwitch 718
UIStepper 718
UIPageControl 719
UIDatePicker 720

UISlider 722
UISegmentedControl 725
UIButton 727
Custom Controls 731
Bars 734
UINavigationBar 734
UIToolbar 738
UITabBar 738
Appearance Proxy 743
26. Modal Dialogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 747
Alert View 748
Action Sheet 750
Dialog Alternatives 754
Local Notifications 755
Part VI. Some Frameworks
27. Audio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 763
System Sounds 763
Audio Session 764
xii | Table of Contents
Interruptions 768
Routing Changes 769
Audio Player 770
Remote Control of Your Sound 773
Playing Sound in the Background 775
Further Topics in Sound 777
28. Video . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 781
MPMoviePlayerController 782
MPMoviePlayerViewController 788
UIVideoEditorController 789
An Introduction to AV Foundation Video 791

29. Music Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 797
Exploring the Music Library 797
The Music Player 801
The Music Picker 806
30.
Photo Library and Image Capture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809
UIImagePickerController 809
Choosing from the Photo Library 809
Using the Camera 811
Image Capture With AV Foundation 815
The Assets Library Framework 817
31. Address Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 823
Address Book Database 823
Address Book Interface 826
ABPeoplePickerNavigationController 826
ABPersonViewController 828
ABNewPersonViewController 829
ABUnknownPersonViewController 829
32.
Calendar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 831
Calendar Database 831
Calendar Interface 838
33. Mail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 845
Mail Message 845
SMS Message 846
Table of Contents | xiii
34. Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 847
Displaying a Map 847
Annotations 849
Overlays 856

35. Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 863
Location 864
Map Kit and Core Location 865
Geocoding 866
Location Manager 868
Heading 872
Acceleration and Attitude 873
Shake Events 874
Raw Acceleration 875
Gyroscope 879
Part VII. Final Topics
36. Persistent Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 887
The Sandbox 887
Basic File Operations 888
Saving and Reading Files 890
User Defaults 891
File Sharing 893
Document Types 894
Handing Off a Document 896
The Document Architecture 899
XML 904
SQLite 911
Image File Formats 912
37. Basic Networking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 915
HTTP Requests 915
Bonjour 923
Push Notifications 925
Beyond Basic Networking 926
38. Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927
The Main Thread 927

Why Threading Is Hard 930
Three Ways of Threading 931
Manual Threads 933
xiv | Table of Contents
NSOperation 934
Grand Central Dispatch 940
Threads and App Backgrounding 943
39. Undo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 947
The Undo Manager 947
The Undo Interface 950
The Undo Architecture 953
40. Epilogue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 957
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 959
Table of Contents | xv

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 re-
markable 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 se-
verely 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 inde-
pendent creature, a leaner, meaner, smarter Cocoa. I could praise Cocoa Touch’s de-
liberate 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.
xvii
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 em-
phasis 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 (start-
ing 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 com-
munication 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.
xviii | Preface
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 ad-
dition 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 funda-
mentals. 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 fu-
ture.
Conventions Used in This Book
The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width
Used for program listings, as well as within paragraphs to refer to program elements
such as variable or function names, databases, data types, environment variables,
statements, and keywords.
Constant width bold
Shows commands or other text that should be typed literally by the user.
Constant width italic
Shows text that should be replaced with user-supplied values or by values deter-

mined by context.
This icon signifies a tip, suggestion, or general note.
Preface | xix
This icon indicates a warning or caution.
Using Code Examples
This book is here to help you get your job done. In general, you may use the code in
this book 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 5 by Matt Neuburg
(O’Reilly). Copyright 2012 Matt Neuburg, 978-1-4493-1934-2.”
If you feel your use of code examples falls outside fair use or the permission given above,
feel free to contact us at
Safari® Books Online
Safari Books Online is an on-demand digital library that lets you easily
search over 7,500 technology and creative reference books and videos to
find the answers you need quickly.
With a subscription, you can read any page and watch any video from our library online.
Read books on your cell phone and mobile devices. Access new titles before they are
available for print, and get exclusive access to manuscripts in development and post
feedback for the authors. Copy and paste code samples, organize your favorites, down-
load chapters, bookmark key sections, create notes, print out pages, and benefit from
tons of other time-saving features.
O’Reilly Media has uploaded this book to the Safari Books Online service. To have full
digital access to this book and others on similar topics from O’Reilly and other pub-

lishers, sign up for free at .
How to Contact Us
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
xx | Preface
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at:
/>To comment or ask technical questions about this book, send email to:

For more information about our books, courses, conferences, and news, see our website
at .
Find us on Facebook: />Follow us on Twitter: />Watch us on YouTube: />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 (), without which I could not
have produced so large a book so painlessly. I was also aided by wonderful software,
including TextMate () and AsciiDoc ( />asciidoc). BBEdit () helped with its diff display. Screenshots
were created with Snapz Pro X () and GraphicConverter
(); diagrams were drawn with OmniGraffle (
nigroup.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 pro-
vided 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
Preface | xxi
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 de-
velopers, 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 de-
velopers 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.
xxii | Preface
Such was the situation in May 2011, when the first edition was formally released, de-
scribing 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 necessi-
tated 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 some-
thing like /Applications/Xcode.app/Contents/Developer. I have not found any other ma-
jor 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 count-
ing), which changes the way in which Objective-C programmers manage object mem-
ory 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
Preface | xxiii

×