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

684 programming iOS 5, 2nd edition covers iOS 5 and xcode 4 3

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 (17.52 MB, 1,014 trang )

www.it-ebooks.info


www.it-ebooks.info


SECOND EDITION

Programming iOS 5

Matt Neuburg

Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo

www.it-ebooks.info


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
March 2012:


Indexer: Matt Neuburg
Cover Designer: Karen Montgomery
Interior Designer: David Futato
Illustrator: Matt Neuburg

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 contained herein.

ISBN: 978-1-449-31934-2
[M]
1331571373

www.it-ebooks.info



Table of Contents

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii

Part I. Language
1. Just Enough C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Compilation, Statements, and Comments
Variable Declaration, Initialization, and Data Types
Structs
Pointers
Arrays
Operators
Flow Control and Conditions
Functions
Pointer Parameters and the Address Operator
Files
The Standard Library
More Preprocessor Directives
Data Type Qualifiers

4
6
8
10
13
14
16
20
23
25

27
28
29

2. Object-Based Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Objects
Messages and Methods
Classes and Instances
Class Methods
Instance Variables
The Object-Based Philosophy

31
32
33
36
37
38

3. Objective-C Objects and Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
An Instance Reference Is a Pointer
Instance References, Initialization, and nil

43
44

iii

www.it-ebooks.info



Instance References and Assignment
Instance References and Memory Management
Messages and Methods
Sending a Message
Declaring a Method
Nesting Method Calls
No Overloading
Parameter Lists
Unrecognized Selectors
Typecasting and the id Type
Messages as Data Type
C Functions
CFTypeRefs
Blocks

47
49
49
50
51
52
53
53
54
56
59
60
62
63


4. Objective-C Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Class and Superclass
Interface and Implementation
Header File and Implementation File
Class Methods
The Secret Life of Classes

67
69
71
73
74

5. Objective-C Instances . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
How Instances Are Created
Ready-Made Instances
Instantiation from Scratch
Nib-Based Instantiation
Polymorphism
The Keyword self
The Keyword super
Instance Variables and Accessors
Key–Value Coding
Properties
How to Write an Initializer

77
77
78

81
82
84
86
89
91
91
94

Part II. IDE
6. Anatomy of an Xcode Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
New Project
The Project Window
The Navigator Pane
The Utilities Pane

100
101
103
107

iv | Table of Contents

www.it-ebooks.info


The Editor
The Project File and Its Dependents
The Target
Build Phases

Build Settings
Configurations
Schemes and Destinations
From Project to App
Build Settings
Property List Settings
Nib Files and Storyboard Files
Other Resources
Code
Frameworks and SDKs

109
111
114
114
115
117
118
120
122
122
123
124
126
128

7. Nib Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
A Tour of the Nib-Editing Interface
The Dock
Canvas

Inspectors and Libraries
Nib Loading and File’s Owner
Making and Loading a Nib
Outlet Connections
More Ways to Create Outlets
More About Outlets
Action Connections
Additional Initialization of Nib-Based Instances

134
135
136
138
140
142
143
148
150
151
155

8. Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
The Documentation Window
Class Documentation Pages
Sample Code
Other Resources
Quick Help
Symbols
Header Files
Internet Resources


158
159
163
164
164
165
165
166

9. Life Cycle of a Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
Choosing a Device Architecture
Localization
Editing Your Code
Autocompletion

169
173
174
175
Table of Contents | v

www.it-ebooks.info


Snippets
Live Syntax Checking and Fix-it
Navigating Your Code
Debugging
Caveman Debugging

The Xcode Debugger
Unit Testing
Static Analyzer
Clean
Running in the Simulator
Running on a Device
Device Management
Version Control
Instruments
Distribution
Ad Hoc Distribution
Final App Preparations
Icons in the App
Other Icons
Launch Images
Screenshots
Property List Settings
Submission to the App Store

176
177
177
180
180
183
188
189
189
190
192

196
196
198
202
204
206
206
207
208
209
209
211

Part III. Cocoa
10. Cocoa Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
Subclassing
Categories
Splitting a Class
Private Method Declarations
Protocols
Optional Methods
Some Foundation Classes
Useful Structs and Constants
NSString and Friends
NSDate and Friends
NSNumber
NSValue
NSData
Equality and Comparison
NSIndexSet


vi | Table of Contents

www.it-ebooks.info

217
220
221
222
223
227
229
229
230
232
232
233
233
234
234


NSArray and NSMutableArray
NSSet and Friends
NSDictionary and NSMutableDictionary
NSNull
Immutable and Mutable
Property Lists
The Secret Life of NSObject


235
236
237
239
239
240
240

11. Cocoa Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
Reasons for Events
Subclassing
Notifications
Receiving a Built-In Notification
Unregistering
NSTimer
Delegation
Data Sources
Actions
The Responder Chain
Deferring Responsibility
Nil-Targeted Actions
Application Lifetime Events
Swamped by Events

246
246
248
249
251
253

253
257
258
263
264
264
265
270

12. Accessors and Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
Accessors
Key–Value Coding
Memory Management
Principles of Cocoa Memory Management
The Golden Rules of Memory Management
What ARC Is and What It Does
How Cocoa Objects Manage Memory
Autorelease
Memory Management of Instance Variables (Non-ARC)
Memory Management of Instance Variables (ARC)
Retain Cycles and Weak References
Nib Loading and Memory Management
Memory Management of Global Variables
Memory Management of Pointer-to-Void Context Info
Memory Management of CFTypeRefs
Properties

275
277
281

281
282
285
288
290
293
297
299
306
307
308
310
313

Table of Contents | vii

www.it-ebooks.info


13. Data Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
Model–View–Controller
Instance Visibility
Visibility by Instantiation
Visibility by Relationship
Global Visibility
Notifications
Key–Value Observing

319
321

322
323
324
325
327

Part IV. Views
14. Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
The Window
Subview and Superview
Frame
Bounds and Center
Layout
Transform
Visibility and Opacity

335
338
341
343
346
349
353

15. Drawing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
UIImage and UIImageView
Graphics Contexts
UIImage Drawing
CGImage Drawing
CIFilter and CIImage

Drawing a UIView
Graphics Context Settings
Paths and Drawing
Clipping
Gradients
Colors and Patterns
Graphics Context Transforms
Shadows
Points and Pixels
Content Mode

355
359
363
364
367
370
372
373
377
378
380
382
384
385
385

16. Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
View and Layer
Layers and Sublayers

Manipulating the Layer Hierarchy
Positioning a Sublayer
viii | Table of Contents

www.it-ebooks.info

390
392
393
394


CAScrollLayer
Layout of Sublayers
Drawing in a Layer
Content Resizing and Positioning
Layers that Draw Themselves
Transforms
Depth
Shadows, Borders, and More
Layers and Key–Value Coding

395
396
396
399
401
403
406
409

411

17. Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
Drawing, Animation, and Threading
UIImageView and UIImage Animation
View Animation
Animation Blocks
Modifying an Animation Block
Transition Animations
Block-Based View Animation
Implicit Layer Animation
Animation Transactions
Media Timing Functions
Core Animation
CABasicAnimation and Its Inheritance
Using a CABasicAnimation
Keyframe Animation
Making a Property Animatable
Grouped Animations
Transitions
The Animations List
Actions
What an Action Is
The Action Search
Hooking Into the Action Search
Nonproperty Actions
Emitter Layers

414
417

419
419
420
424
425
430
431
432
434
434
436
439
440
441
445
447
449
449
450
451
454
455

18. Touches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
Touch Events and Views
Receiving Touches
Restricting Touches
Interpreting Touches
Gesture Recognizers
Gesture Recognizer Classes


464
466
467
468
473
473
Table of Contents | ix

www.it-ebooks.info


Multiple Gesture Recognizers
Subclassing Gesture Recognizers
Gesture Recognizer Delegate
Touch Delivery
Hit-Testing
Initial Touch Event Delivery
Gesture Recognizer and View
Touch Exclusion Logic
Recognition
Touches and the Responder Chain

477
479
481
483
484
489
490

491
492
493

Part V. Interface
19. View Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
The View Controller Hierarchy
View Controller and View Creation
Manual View
Generic Automatic View
View in a Separate Nib
Nib-Instantiated View Controller
Storyboard-Instantiated View Controller
Rotation
Rotation Events
Initial Orientation
Presented View Controller
Presented View Animation
Presentation Styles
Presented Views and Rotation
Tab Bar Controllers
Tab Bar Items
Configuring a Tab Bar Controller
Navigation Controllers
Bar Button Items
Navigation Items
Toolbar Items
Configuring a Navigation Controller
Page View Controller
Container View Controllers

Storyboards
View Controller Lifetime Events
View Controller Memory Management

x | Table of Contents

www.it-ebooks.info

500
504
507
509
511
514
517
519
521
523
526
531
532
534
536
537
538
540
544
546
549
549

551
554
557
562
564


20. Scroll Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
Creating a Scroll View
Scrolling
Paging
Tiling
Zooming
Zooming Programmatically
Zooming with Detail
Scroll View Delegate
Scroll View Touches
Scroll View Performance

570
573
576
577
579
581
581
584
586
591


21. Table Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593
Table View Cells
Built-In Cell Styles
Custom Cells
Table View Data
The Three Big Questions
Table View Sections
Refreshing Table View Data
Variable Row Heights
Table View Selection
Table View Scrolling and Layout
Table View Searching
Table View Editing
Deleting Table Items
Editable Content in Table Items
Inserting Table Items
Rearranging Table Items
Dynamic Table Content
Table View Menus

596
597
603
611
612
616
619
621
623
629

630
636
639
640
642
644
645
646

22. Popovers and Split Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649
Configuring and Displaying a Popover
Managing a Popover
Dismissing a Popover
Popover Segues
Automatic Popovers
Split Views

651
656
657
660
661
663

23. Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671
UILabel
UITextField

672
673

Table of Contents | xi

www.it-ebooks.info


Editing and the Keyboard
Configuring the Keyboard
Text Field Delegate and Control Event Messages
The Text Field Menu
UITextView
Core Text

676
680
681
683
685
688

24. Web Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697
Loading Content
Communicating with a Web View

698
704

25. Controls and Other Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 707
UIActivityIndicatorView
UIProgressView
UIPickerView

UISearchBar
UIControl
UISwitch
UIStepper
UIPageControl
UIDatePicker
UISlider
UISegmentedControl
UIButton
Custom Controls
Bars
UINavigationBar
UIToolbar
UITabBar
Appearance Proxy

707
708
711
713
716
718
718
719
720
722
725
727
731
734

734
738
738
743

26. Modal Dialogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 747
Alert View
Action Sheet
Dialog Alternatives
Local Notifications

748
750
754
755

Part VI. Some Frameworks
27. Audio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 763
System Sounds
Audio Session

763
764

xii | Table of Contents

www.it-ebooks.info


Interruptions

Routing Changes
Audio Player
Remote Control of Your Sound
Playing Sound in the Background
Further Topics in Sound

768
769
770
773
775
777

28. Video . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 781
MPMoviePlayerController
MPMoviePlayerViewController
UIVideoEditorController
An Introduction to AV Foundation Video

782
788
789
791

29. Music Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 797
Exploring the Music Library
The Music Player
The Music Picker

797

801
806

30. Photo Library and Image Capture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809
UIImagePickerController
Choosing from the Photo Library
Using the Camera
Image Capture With AV Foundation
The Assets Library Framework

809
809
811
815
817

31. Address Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 823
Address Book Database
Address Book Interface
ABPeoplePickerNavigationController
ABPersonViewController
ABNewPersonViewController
ABUnknownPersonViewController

823
826
826
828
829
829


32. Calendar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 831
Calendar Database
Calendar Interface

831
838

33. Mail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 845
Mail Message
SMS Message

845
846

Table of Contents | xiii

www.it-ebooks.info


34. Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 847
Displaying a Map
Annotations
Overlays

847
849
856

35. Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 863

Location
Map Kit and Core Location
Geocoding
Location Manager
Heading
Acceleration and Attitude
Shake Events
Raw Acceleration
Gyroscope

864
865
866
868
872
873
874
875
879

Part VII. Final Topics
36. Persistent Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 887
The Sandbox
Basic File Operations
Saving and Reading Files
User Defaults
File Sharing
Document Types
Handing Off a Document
The Document Architecture

XML
SQLite
Image File Formats

887
888
890
891
893
894
896
899
904
911
912

37. Basic Networking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 915
HTTP Requests
Bonjour
Push Notifications
Beyond Basic Networking

915
923
925
926

38. Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927
The Main Thread
Why Threading Is Hard

Three Ways of Threading
Manual Threads

927
930
931
933

xiv | Table of Contents

www.it-ebooks.info


NSOperation
Grand Central Dispatch
Threads and App Backgrounding

934
940
943

39. Undo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 947
The Undo Manager
The Undo Interface
The Undo Architecture

947
950
953


40. Epilogue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 957
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 959

Table of Contents | xv

www.it-ebooks.info


www.it-ebooks.info


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.
xvii

www.it-ebooks.info


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.

xviii | Preface

www.it-ebooks.info


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 determined by context.
This icon signifies a tip, suggestion, or general note.

Preface | xix

www.it-ebooks.info


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, download 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 publishers, 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

www.it-ebooks.info


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 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
Preface | xxi

www.it-ebooks.info


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.


xxii | Preface

www.it-ebooks.info


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
Preface | xxiii

www.it-ebooks.info


×