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

programming ios 6 3rd edition

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 (20.44 MB, 1,185 trang )

www.it-ebooks.info
www.it-ebooks.info
Matt Neuburg
THIRD EDITION
Programming iOS 6
www.it-ebooks.info
Programming iOS 6, Third Edition
by Matt Neuburg
Copyright © 2013 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: Rachel Roumeliotis
Production Editor: Kristen Borg
Proofreader: O’Reilly Production Services
Indexer: Matt Neuburg
Cover Designer: Randy Comer
Interior Designer: David Futato
Illustrator: Matt Neuburg
March 2013:
Third Edition
Revision History for the Third Edition:
2013-02-27: 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 6, 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 trade‐


mark 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 contained
herein.
ISBN: 978-1-449-36576-9
[LSI]
www.it-ebooks.info
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
Part I. Language
1.
Just Enough C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Compilation, Statements, and Comments 5
Variable Declaration, Initialization, and Data Types 6
Structs 9
Pointers 11
Arrays 14
Operators 15
Flow Control and Conditions 17
Functions 21
Pointer Parameters and the Address Operator 24
Files 26
The Standard Library 30
More Preprocessor Directives 30
Data Type Qualifiers 31
2.
Object-Based Programming. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Objects 35
Messages and Methods 36
Classes and Instances 37

Class Methods 40
Instance Variables 41
The Object-Based Philosophy 42
3.
Objective-C Objects and Messages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
An Instance Reference Is a Pointer 47
iii
www.it-ebooks.info
Instance References, Initialization, and nil 49
Instance References and Assignment 51
Instance References and Memory Management 52
Messages and Methods 54
Sending a Message 54
Declaring a Method 55
Nesting Method Calls 56
No Overloading 57
Parameter Lists 58
Unrecognized Selectors 59
Typecasting and the id Type 61
Messages as Data Type 65
C Functions 66
CFTypeRefs 67
Blocks 68
4. Objective-C Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Class and Superclass 75
Interface and Implementation 77
Header File and Implementation File 79
Class Methods 82
The Secret Life of Classes 83
5.

Objective-C Instances. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
How Instances Are Created 85
Ready-Made Instances 85
Instantiation from Scratch 87
Nib-Based Instantiation 90
Polymorphism 91
The Keyword self 93
The Keyword super 97
Instance Variables and Accessors 98
Key–Value Coding 100
Properties 102
How to Write an Initializer 104
Part II. IDE
6.
Anatomy of an Xcode Project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
New Project 110
The Project Window 112
iv | Table of Contents
www.it-ebooks.info
The Navigator Pane 113
The Utilities Pane 118
The Editor 119
The Project File and Its Dependents 122
The Target 125
Build Phases 125
Build Settings 126
Configurations 128
Schemes and Destinations 129
From Project to App 131
Build Settings 133

Property List Settings 133
Nib Files and Storyboard Files 134
Other Resources 135
Code 137
Frameworks and SDKs 139
7. Nib Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
A Tour of the Nib-Editing Interface 146
The Dock 147
Canvas 148
Inspectors and Libraries 151
Nib Loading and File’s Owner 153
Making and Loading a Nib 154
Outlet Connections 156
More Ways to Create Outlets 161
More About Outlets 164
Action Connections 165
Additional Initialization of Nib-Based Instances 168
8.
Documentation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
The Documentation Window 172
Class Documentation Pages 174
Sample Code 177
Other Resources 178
Quick Help 178
Symbols 179
Header Files 180
Internet Resources 180
9.
Life Cycle of a Project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
Device Architecture and Conditional Code 183

Table of Contents | v
www.it-ebooks.info
Localization 188
Editing Your Code 192
Autocompletion 193
Snippets 195
Fix-it and Live Syntax Checking 195
Navigating Your Code 196
Debugging 199
Caveman Debugging 199
The Xcode Debugger 202
Unit Testing 208
Static Analyzer 208
Clean 209
Running in the Simulator 210
Running on a Device 212
Profile and Device Management 215
Version Control 216
Instruments 219
Distribution 223
Ad Hoc Distribution 225
Final App Preparations 226
Icons in the App 226
Other Icons 227
Launch Images 228
Screenshots 230
Property List Settings 231
Submission to the App Store 233
Part III. Cocoa
10.

Cocoa Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
Subclassing 239
Categories 242
Splitting a Class 243
Class Extensions 244
Protocols 245
Optional Methods 250
Some Foundation Classes 252
Useful Structs and Constants 252
NSString and Friends 253
NSDate and Friends 255
NSNumber 256
vi | Table of Contents
www.it-ebooks.info
NSValue 257
NSData 257
Equality and Comparison 258
NSIndexSet 258
NSArray and NSMutableArray 259
NSSet and Friends 261
NSDictionary and NSMutableDictionary 262
NSNull 264
Immutable and Mutable 264
Property Lists 265
The Secret Life of NSObject 266
11. Cocoa Events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
Reasons for Events 270
Subclassing 270
Notifications 272
Receiving a Built-In Notification 273

Unregistering 275
NSTimer 276
Delegation 277
Data Sources 280
Actions 281
The Responder Chain 283
Deferring Responsibility 284
Nil-Targeted Actions 285
Swamped by Events 286
Delayed Performance 289
Application Lifetime Events 292
12.
Accessors and Memory Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
Key–Value Coding 298
KVC and Outlets 300
Key Paths and Array Accessors 301
Memory Management 303
Principles of Cocoa Memory Management 303
The Golden Rules of Memory Management 305
What ARC Is and What It Does 307
How Cocoa Objects Manage Memory 310
Autorelease 312
Memory Management of Instance Variables (Non-ARC) 316
Memory Management of Instance Variables (ARC) 320
Retain Cycles and Weak References 321
Table of Contents | vii
www.it-ebooks.info
Unusual Memory Management Situations 324
Nib Loading and Memory Management 329
Memory Management of Global Variables 330

Memory Management of Pointer-to-Void Context Info 331
Memory Management of CFTypeRefs 332
Properties 335
Property Memory Management Policies 336
Property Declaration Syntax 338
Property Accessor Synthesis 340
Dynamic Accessors 342
13.
Data Communication. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
Model–View–Controller 347
Instance Visibility 349
Visibility by Instantiation 350
Visibility by Relationship 351
Global Visibility 352
Notifications 353
Key–Value Observing 354
Part IV. Views
14.
Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
The Window 364
Subview and Superview 367
Visibility and Opacity 369
Frame 370
Bounds and Center 371
Transform 375
Layout 380
Autoresizing 381
Autolayout 383
Constraints in the Nib 393
Order of Layout Events 398

Autolayout and View Transforms 399
15.
Drawing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
UIImage and UIImageView 403
Graphics Contexts 409
UIImage Drawing 412
CGImage Drawing 414
viii | Table of Contents
www.it-ebooks.info
CIFilter and CIImage 418
Drawing a UIView 421
Graphics Context Settings 423
Paths and Drawing 425
Clipping 429
Gradients 430
Colors and Patterns 432
Graphics Context Transforms 434
Shadows 436
Points and Pixels 437
Content Mode 438
16. Layers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
View and Layer 442
Layers and Sublayers 444
Manipulating the Layer Hierarchy 446
Positioning a Sublayer 446
CAScrollLayer 447
Layout of Sublayers 448
Drawing in a Layer 449
Content Resizing and Positioning 452
Layers that Draw Themselves 455

Transforms 456
Depth 460
Shadows, Borders, and More 463
Layer Efficiency 464
Layers and Key–Value Coding 466
17.
Animation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
Drawing, Animation, and Threading 470
UIImageView and UIImage Animation 472
View Animation 475
Animation Blocks 475
Modifying an Animation Block 476
Transition Animations 480
Block-Based View Animation 481
Implicit Layer Animation 487
Animation Transactions 488
Media Timing Functions 489
Core Animation 491
CABasicAnimation and Its Inheritance 491
Using a CABasicAnimation 493
Table of Contents | ix
www.it-ebooks.info
Keyframe Animation 497
Making a Property Animatable 498
Grouped Animations 499
Transitions 503
The Animations List 505
Animation and Autolayout 507
Actions 511
What an Action Is 511

The Action Search 511
Hooking Into the Action Search 513
Nonproperty Actions 516
Emitter Layers 517
CIFilter Transitions 523
18.
Touches. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
Touch Events and Views 528
Receiving Touches 530
Restricting Touches 531
Interpreting Touches 532
Gesture Recognizers 537
Gesture Recognizer Classes 538
Multiple Gesture Recognizers 543
Subclassing Gesture Recognizers 544
Gesture Recognizer Delegate 546
Gesture Recognizers in the Nib 549
Touch Delivery 550
Hit-Testing 551
Initial Touch Event Delivery 556
Gesture Recognizer and View 556
Touch Exclusion Logic 558
Recognition 558
Touches and the Responder Chain 560
Part V. Interface
19.
View Controllers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565
The View Controller Hierarchy 568
View Controller and View Creation 572
Manual View 575

Generic Automatic View 578
View in a Separate Nib 579
x | Table of Contents
www.it-ebooks.info
Nib-Instantiated View Controller 583
Storyboard-Instantiated View Controller 585
Rotation 588
Rotation and Layout Events 592
Initial Orientation 595
Presented View Controller 599
Presented View Animation 604
Presentation Styles 605
Rotation of a Presented View 608
Presenting a View in Response to Rotation 609
Tab Bar Controllers 610
Tab Bar Items 611
Configuring a Tab Bar Controller 612
Navigation Controllers 614
Bar Button Items 617
Navigation Items 619
Toolbar Items 622
Configuring a Navigation Controller 622
Page View Controller 625
Container View Controllers 630
Storyboards 633
Segues 635
Unwind Segues 637
Storyboards and Custom Container View Controllers 642
View Controller Lifetime Events 642
View Controller Memory Management 646

State Restoration 649
Participating in State Restoration 651
Restoration ID and Restoration Class 653
Restoring View Controller State 661
20.
Scroll Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667
Creating a Scroll View 667
Scrolling 673
Paging 676
Tiling 677
Zooming 679
Zooming Programmatically 682
Zooming with Detail 682
Scroll View Delegate 685
Scroll View Touches 687
Table of Contents | xi
www.it-ebooks.info
Scroll View Performance 692
21. Table Views and Collection Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 695
Table View Cells 698
Built-In Cell Styles 699
Registering a Cell Class 705
Custom Cells 708
Table View Data 715
The Three Big Questions 716
Table View Sections 719
Refreshing Table View Data 726
Variable Row Heights 729
Table View Selection 732
Table View Scrolling and Layout 737

Table View State Restoration 738
Table View Searching 739
Table View Editing 745
Deleting Table Items 749
Editable Content in Table Items 750
Inserting Table Items 752
Rearranging Table Items 754
Dynamic Table Content 755
Table View Menus 756
Collection Views 758
22.
Popovers and Split Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 767
Configuring and Displaying a Popover 769
Managing a Popover 774
Dismissing a Popover 774
Popovers and Presented Views 778
Popover Segues 778
Automatic Popovers 780
Split Views 782
23.
Text. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787
Attributed Strings 788
UILabel 797
UITextField 800
Summoning and Dismissing the Keyboard 803
Keyboard Covers Text Field 804
Configuring the Keyboard 808
Text Field Delegate and Control Event Messages 809
xii | Table of Contents
www.it-ebooks.info

The Text Field Menu 812
UITextView 814
Core Text 817
24. Web Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 825
Loading Web View Content 826
Web View State Restoration 833
Communicating with a Web View 834
25. Controls and Other Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 837
UIActivityIndicatorView 837
UIProgressView 839
UIPickerView 841
UISearchBar 843
UIControl 847
UISwitch 852
UIStepper 853
UIPageControl 854
UIDatePicker 855
UISlider 858
UISegmentedControl 861
UIButton 865
Custom Controls 870
Bars 873
UINavigationBar 873
UIToolbar 878
UITabBar 879
Appearance Proxy 883
26.
Modal Dialogs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 887
Alert View 888
Action Sheet 891

Dialog Alternatives 896
Local Notifications 897
Activity View 900
Part VI. Some Frameworks
27.
Audio. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 909
System Sounds 909
Audio Session 910
Table of Contents | xiii
www.it-ebooks.info
Interruptions 913
Routing Changes 915
Audio Player 916
Remote Control of Your Sound 918
Playing Sound in the Background 921
Further Topics in Sound 923
28.
Video. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 925
MPMoviePlayerController 926
MPMoviePlayerViewController 932
UIVideoEditorController 934
Introduction to AV Foundation Video 936
29.
Music Library. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 943
Exploring the Music Library 943
The Music Player 948
The Music Picker 954
30.
Photo Library and Image Capture. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 957
UIImagePickerController 957

Choosing from the Photo Library 958
Using the Camera 962
Image Capture With AV Foundation 966
The Assets Library Framework 969
31.
Address Book. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 973
Address Book Database 973
Address Book Interface 977
ABPeoplePickerNavigationController 978
ABPersonViewController 980
ABNewPersonViewController 981
ABUnknownPersonViewController 982
32.
Calendar. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 985
Calendar Database 985
Calendar Interface 995
33.
Mail and Messages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1003
Mail Message 1003
Text Message 1005
xiv | Table of Contents
www.it-ebooks.info
Twitter Post 1006
34. Maps. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1007
Displaying a Map 1007
Annotations 1010
Overlays 1017
Map Kit and Current Location 1024
Geocoding 1025
Communicating With the Maps App 1027

35. Sensors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1029
Location 1030
Heading 1035
Acceleration and Attitude 1036
Shake Events 1037
Raw Acceleration 1038
Gyroscope 1042
Part VII. Final Topics
36.
Persistent Storage. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1051
The Sandbox 1052
Basic File Operations 1053
Saving and Reading Files 1054
User Defaults 1056
File Sharing 1058
Document Types 1059
Handing Off a Document 1060
The Document Architecture 1064
iCloud 1068
XML 1070
SQLite 1077
Core Data 1078
Image File Formats 1084
37.
Basic Networking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1087
HTTP Requests 1087
Bonjour 1096
Push Notifications 1098
Table of Contents | xv
www.it-ebooks.info

Beyond Basic Networking 1099
38. Threads. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1101
The Main Thread 1101
Why Threading Is Hard 1104
Three Ways of Threading 1106
Manual Threads 1107
NSOperation 1109
Grand Central Dispatch 1114
Threads and App Backgrounding 1119
39.
Undo. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1123
The Undo Manager 1123
The Undo Interface 1127
The Undo Architecture 1130
40.
Epilogue. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1133
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1135
xvi | Table of Contents
www.it-ebooks.info
Aut lego vel scribo; doceo scrutorve sophian.
—Sedulius Scottus
Preface
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 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 ex‐
xvii
www.it-ebooks.info
amples. Where Mac OS X’s animation layers are glommed onto views as a kind of af‐
terthought, 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

xviii | Preface
www.it-ebooks.info
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.
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.
Preface | xix
www.it-ebooks.info
This icon signifies a tip, suggestion, or general note.
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 6 by Matt Neuburg
(O’Reilly). Copyright 2013 Matt Neuburg, 978-1-449-36576-9.”
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 .
xx | Preface
www.it-ebooks.info
How to Contact Us
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)
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 (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.
Preface | xxi
www.it-ebooks.info
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 en‐
couragement. 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 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
xxii | Preface
www.it-ebooks.info
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.
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 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 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
Preface | xxiii
www.it-ebooks.info

×