Tải bản đầy đủ (.pdf) (928 trang)

Programming iOS 5 pptx

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 (11.39 MB, 928 trang )

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
Revision History for the :
Dec 23, 2011
See for release details.
ISBN: 978-1-449-31934-2
1326317995
www.it-ebooks.info
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 12
Operators 13
Flow Control and Conditions 15
Functions 20
Pointer Parameters and the Address Operator 22
Files 24
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
www.it-ebooks.info
Instance References and Assignment 47
Instance References and Memory Management 48
Messages and Methods 50
Sending a Message 50
Declaring a Method 51
Nesting Method Calls 52
No Overloading 53
Parameter Lists 54
Unrecognized Selectors 54
Typecasting and the id Type 56
Messages as Data Type 60
C Functions 61
C Struct Pointers 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 87
Instance Variables and Accessors 89
Key–Value Coding 91
Properties 92
How to Write an Initializer 94
Part II. IDE
6. Anatomy of an Xcode Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
New Project 99
The Project Window 101
The Navigator Pane 103
The Utilities Pane 107
iv | Table of Contents
www.it-ebooks.info
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
www.it-ebooks.info
Snippets 176
Live Syntax Checking and Fix-it 177

Navigating Your Code 178
Debugging 180
Caveman Debugging 180
The Xcode Debugger 183
Static Analyzer 188
Clean 189
Running in the Simulator 190
Running on a Device 191
Device Management 195
Version Control 196
Instruments 198
Distribution 202
Ad Hoc Distribution 204
Final App Preparations 205
Icons in the App 206
Other Icons 207
Launch Images 207
Screenshots 208
Property List Settings 209
Submission to the App Store 210
Part III. Cocoa
10. Cocoa Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Subclassing 215
Categories 218
Splitting a Class 219
Private Method Declarations 220
Protocols 221
Optional Methods 226
Some Foundation Classes 227
Useful Structs and Constants 227

NSString and Friends 228
NSDate and Friends 230
NSNumber 230
NSValue 231
NSData 231
Equality and Comparison 232
NSIndexSet 232
NSArray and NSMutableArray 233
vi | Table of Contents
www.it-ebooks.info
NSSet and Friends 234
NSDictionary and NSMutableDictionary 235
NSNull 237
Immutable and Mutable 237
Property Lists 238
The Secret Life of NSObject 238
11. Cocoa Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
Reasons for Events 244
Subclassing 244
Notifications 246
Receiving a Built-In Notification 247
Unregistering 249
NSTimer 251
Delegation 251
Data Sources 255
Actions 256
The Responder Chain 261
Deferring Responsibility 261
Nil-Targeted Actions 262
Application Lifetime Events 263

Swamped by Events 268
12. Accessors and Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
Accessors 273
Key–Value Coding 275
Memory Management 279
Principles of Cocoa Memory Management 279
The Golden Rules of Memory Management 281
What ARC Is and What It Does 283
How Cocoa Objects Manage Memory 286
Autorelease 288
Memory Management of Instance Variables (Non-ARC) 291
Memory Management of Instance Variables (ARC) 295
Retain Cycles and Weak References 297
Nib Loading and Memory Management 303
Memory Management of Global Variables 305
Memory Management of Pointer-to-Void Context Info 306
Memory Management of CFTypeRefs 308
Properties 310
13.
Data Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
Model–View–Controller 317
Table of Contents | vii
www.it-ebooks.info
Instance Visibility 319
Visibility by Instantiation 320
Visibility by Relationship 321
Global Visibility 322
Notifications 323
Key–Value Observing 324
Part IV. Views

14. Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
The Window 333
Subview and Superview 336
Frame 339
Bounds and Center 341
Layout 344
Transform 347
Visibility and Opacity 351
15. Drawing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
UIImage and UIImageView 353
Graphics Contexts 357
UIImage Drawing 361
CGImage Drawing 362
CIFilter and CIImage 365
Drawing a UIView 368
Graphics Context Settings 370
Paths and Drawing 371
Clipping 375
Gradients 376
Colors and Patterns 378
Graphics Context Transforms 380
Shadows 382
Points and Pixels 383
Content Mode 383
16. Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
View and Layer 388
Layers and Sublayers 390
Manipulating the Layer Hierarchy 391
Positioning a Sublayer 392
CAScrollLayer 393

Layout of Sublayers 394
viii | Table of Contents
www.it-ebooks.info
Drawing in a Layer 394
Content Resizing and Positioning 397
Layers that Draw Themselves 399
Transforms 400
Depth 404
Shadows, Borders, and More 406
Layers and Key–Value Coding 409
17. Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
Drawing, Animation, and Threading 412
UIImageView and UIImage Animation 415
View Animation 417
Animation Blocks 417
Modifying an Animation Block 418
Transition Animations 422
Block-Based View Animation 423
Implicit Layer Animation 428
Animation Transactions 429
Media Timing Functions 430
Core Animation 432
CABasicAnimation and Its Inheritance 432
Using a CABasicAnimation 434
Keyframe Animation 437
Making a Property Animatable 438
Grouped Animations 439
Transitions 443
The Animations List 445
Actions 447

What an Action Is 447
The Action Search 448
Hooking Into the Action Search 449
Nonproperty Actions 452
Emitter Layers 453
18. Touches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
Touch Events and Views 462
Receiving Touches 464
Restricting Touches 465
Interpreting Touches 466
Gesture Recognizers 471
Gesture Recognizer Classes 471
Multiple Gesture Recognizers 476
Subclassing Gesture Recognizers 477
Table of Contents | ix
www.it-ebooks.info
Gesture Recognizer Delegate 479
Touch Delivery 481
Hit-Testing 482
Initial Touch Event Delivery 487
Gesture Recognizer and View 488
Touch Exclusion Logic 489
Recognition 490
Touches and the Responder Chain 491
Part V. Interface
19.
View Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
The View Controller Hierarchy 498
View Controller and View Creation 502
Manual View 505

Generic Automatic View 507
View in a Separate Nib 509
Nib-Instantiated View Controller 512
Storyboard-Instantiated View Controller 515
Rotation 517
Initial Orientation 519
Rotation Events 522
Presented View Controller 523
Presented View Animation 528
Presentation Styles 529
Presented Views and Rotation 532
Tab Bar Controllers 534
Tab Bar Items 535
Configuring a Tab Bar Controller 536
Navigation Controllers 538
Bar Button Items 542
Navigation Items 544
Toolbar Items 546
Configuring a Navigation Controller 547
Page View Controller 549
Container View Controllers 552
Storyboards 554
View Controller Lifetime Events 560
View Controller Memory Management 562
20. Scroll Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
Creating a Scroll View 568
x | Table of Contents
www.it-ebooks.info
Scrolling 571
Paging 574

Tiling 575
Zooming 577
Zooming Programmatically 579
Zooming with Detail 579
Scroll View Delegate 582
Scroll View Touches 584
Scroll View Performance 589
21.
Table Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591
Table View Cells 594
Built-In Cell Styles 595
Custom Cells 601
Table View Data 609
The Three Big Questions 610
Table View Sections 614
Refreshing Table View Data 618
Variable Row Heights 619
Table View Selection 621
Table View Scrolling and Layout 627
Table View Searching 628
Table View Editing 634
Deleting Table Items 637
Editable Content in Table Items 638
Inserting Table Items 640
Rearranging Table Items 642
Dynamic Table Content 643
Table View Menus 644
22. Popovers and Split Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647
Configuring and Displaying a Popover 649
Managing a Popover 654

Dismissing a Popover 654
Popover Segues 658
Automatic Popovers 659
Split Views 661
23. Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667
UILabel 668
UITextField 669
Editing and the Keyboard 672
Configuring the Keyboard 676
Table of Contents | xi
www.it-ebooks.info
Text Field Delegate and Control Event Messages 677
The Text Field Menu 679
UITextView 681
Core Text 684
24. Web Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693
Loading Content 694
Communicating with a Web View 700
25. Controls and Other Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703
UIActivityIndicatorView 703
UIProgressView 704
UIPickerView 707
UISearchBar 709
UIControl 712
UISwitch 714
UIStepper 714
UIPageControl 715
UIDatePicker 716
UISlider 718
UISegmentedControl 721

UIButton 723
Custom Controls 727
Bars 730
UINavigationBar 730
UIToolbar 734
UITabBar 735
Appearance Proxy 739
26. Modal Dialogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 743
Alert View 744
Action Sheet 746
Dialog Alternatives 750
Local Notifications 751
Part VI. Some Frameworks
27. Audio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 759
System Sounds 759
Audio Session 760
Audio Player 764
Remote Control of Your Sound 766
xii | Table of Contents
www.it-ebooks.info
Playing Sound in the Background 768
Further Topics in Sound 769
28. Video . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 771
MPMoviePlayerController 772
MPMoviePlayerViewController 777
UIVideoEditorController 778
Further Topics in Video 779
29. Music Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 783
Exploring the Music Library 783
The Music Player 787

The Music Picker 791
30. Photo Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 795
UIImagePickerController 795
Choosing from the Photo Library 796
Using the Camera 797
The Assets Library Framework 800
31. Address Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 803
Address Book Database 803
Address Book Interface 805
ABPeoplePickerNavigationController 806
ABPersonViewController 808
ABNewPersonViewController 808
ABUnknownPersonViewController 809
32. Calendar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 811
Calendar Database 811
Calendar Interface 816
33. Mail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 819
Mail Message 819
SMS Message 820
34. Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 821
Presenting a Map 821
Annotations 823
Overlays 828
Table of Contents | xiii
www.it-ebooks.info
35. Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 833
Location 833
Heading and Course 836
Acceleration 837
Shake Events 837

UIAccelerometer 838
Core Motion 841
Part VII. Final Topics
36.
Persistent Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 845
The Sandbox 845
Basic File Operations 846
Saving and Reading Files 847
User Defaults 849
File Sharing 851
Document Types 851
Handing Off a Document 853
XML 856
SQLite 862
Image File Formats 863
37. Basic Networking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 867
HTTP Requests 867
Bonjour 873
Push Notifications 875
Beyond Basic Networking 876
38. Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 877
The Main Thread 877
Why Threading Is Hard 880
Three Ways of Threading 881
Manual Threads 883
NSOperation 884
Grand Central Dispatch 889
Threads and App Backgrounding 891
39. Undo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 895
The Undo Manager 895

The Undo Interface 898
The Undo Architecture 901
xiv | Table of Contents
www.it-ebooks.info
40. Epilogue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 903
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 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
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 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
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 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.
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
Preface | xix
www.it-ebooks.info
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, screen shots 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.
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.
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
xx | Preface
www.it-ebooks.info
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.
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
book I therefore assume throughout that you do have it turned on. In Chapter 12, where
I discuss memory management, I still describe what life is like without ARC, as I did
in the previous edition; but, outside that chapter, all code examples, unless specifically
state otherwise, are supposed to be running under ARC. If you start a new Xcode
project with File → New Project and pick any iOS application template, then if “Use
Automatic Reference Counting” is checked in the second screen, you’re using ARC.
iOS 5 also introduces storyboards. A storyboard file is similar to a nib file: it’s a place
where Xcode lets you “draw” parts of the interface. The main difference is that a single
storyboard file can do the work of multiple nib files. Nib files and storyboard files are
not identical, nor are they used identically, but because of their similarity, when I speak
of a nib file generically, in this book, I mean a nib or storyboard file, indifferently. I’ll
try to indicate this at the time, but the reader will forgive me if I don’t keep saying “nib
or storyboard” all the time.
Preface | xxi
www.it-ebooks.info
In closing, I should like to say a few words to the people who have, in my opinion,
gratuitously criticized the previous edition of this book on one or more of the following
grounds:
a. It isn’t a “cookbook” (a book full of step-by-step instructions for creating full

working applications).
b. It devotes hundreds of pages to fundamentals.
c. It doesn’t get the reader started early on with hands-on programming; there isn’t
even a “Hello, World” tutorial.
All of that is perfectly true. It is also quite deliberate. As both the table of contents and
this preface are at pains to make clear, this is not that type of book. To paraphrase
Butler’s Law, this book is the type of book it is, and not some other type. That’s why
I wrote this book in the first place. The books of the type that these critics seem to want
this book to be exist by the score; books of the type that this book is, however, seemed
to me not to exist at all. As with all my other books, so with this one: when I couldn’t
find the book I wanted, I wrote it myself. I expect this book to be useful to those who
need this type of book. People who prefer some other type of book should get some
other type of book, and not mar my book’s Web page by criticizing it for not being
what it was never intended to be.
The purpose of this book is to proceed by focusing on the underlying knowledge needed
for an actual understanding of iOS programming. That is precisely the opposite of a
cookbook. This book has no simple recipes ready for you to drop into your own code
and come up with an app. I don’t give you some fish; I teach you what a fish is and
what you need to know to obtain one. The number of books out there that skip blithely
past the fundamentals, leaving the reader to pick up Objective-C somehow independ-
ently, is painfully huge. The result is that numerous learners are encouraged to try their
hand at programming when, to judge from the nature of the questions they ask and the
confusion they exhibit, they don’t understand what they are doing. This book acts as
a corrective, and this requires that space be devoted to fundamentals. The book does
not hold a gun to your head and force you to read all about all of those fundamentals;
if you already know everything there is to know about C, about Objective-C, about
Xcode, about Cocoa, about views and drawing or whatever (but do you? do you
really?), then by all means, skip those opening chapters. But don’t begrudge to the
people who need them the explanations that this book contains, as those are the people
at whom they are aimed.

That explains why there’s no attempt, in this book, to rush the reader into hands-on
programming. My book does not pander to a desire for the false, cheap gratification of
making believe that one is a programmer merely because one can parrot some instruc-
tions. My book is about knowledge — hard-won, rigorously gained knowledge. It’s
about gaining an understanding of what you are doing when you program iOS 5. It
calls for a substantial investment of time and thought, and many pages elapse before
any practical programming is demonstrated.
xxii | Preface
www.it-ebooks.info
However, the complaint that the reader of my book doesn’t get to run any code is
factually false. The book is crammed full of substantial code examples — all of which,
moreover, are available for download from my GitHub site ( />neub), so you can download them, run them in Xcode, and play with them to your
heart’s content. So you can and should, in fact, be running code right from the outset.
Nevertheless, the purpose of the code in this book is not for the fun of running it. All
of my code is to support your understanding of whatever concepts I’m explaining at
that point in the book.
In any case, perfectly good hands-on “Hello, World” tutorials are a dime a dozen;
they’re plastered all over the Internet, including at Apple’s own site (http://developer
.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhone101/Articles/). You
don’t need me to show you that the process of writing a trivial iPhone application is
fun and easy.
Still, for those who feel strongly that I haven’t done my job unless I supply a “Hello,
World” example, here is one, complete with step-by-step instructions:
1. Install Xcode 4.2, and launch the Xcode application.
2. Choose File → New → New Project.
3. In the “Choose a template” dialog, under “iOS” on the left (not “Mac OS X”), click
Application. On the right, click Empty Application. Click Next.
4. For Product Name, type Hello. Enter a company identifier if there isn’t one already,
such as com.yourLastName.yourFirstName. Choose Device Family: iPhone. Uncheck
all three checkboxes. Click Next.

5. Navigate to the Desktop. Uncheck “Create local git repository.” Click Create.
6. The project window opens. Press Command-1. At the left, click AppDelegate.m.
7. Work in the editor in the middle of the window. Look for the words “Override
point for customization after application launch.” Place the cursor to the right of
those words and hit Return a few times, to make some white space. Click in that
white space and type these lines of code:
UILabel* label = [[UILabel alloc] init];
label.text = @"Hello, world!";
[label sizeToFit];
CGRect f = label.frame;
f.origin = CGPointMake(100,100);
label.frame = f;
[self.window addSubview:label];
8. Press Command-R. If you see a dialog asking whether you want to save, accept.
9. After a while, the iOS Simulator application appears, containing a white window
with “Hello, world!” in it.
Congratulations. You’ve made a “Hello, world” example. Wasn’t that easy? Wasn’t it
boring? Wasn’t it pointless? And are you any the wiser as to what, in fact, you just did?
Preface | xxiii
www.it-ebooks.info
To find out — and, even more important, to know enough to be able to progress further
on your own — read this book.
xxiv | Preface
www.it-ebooks.info
PART I
Language
Apple has provided a vast toolbox for programming iOS to make an app come to life
and behave the way you want it to. That toolbox is the API (application programming
interface). To use the API, you must speak the API’s language. That language, for the
most part, is Objective-C, which itself is built on top of C; some pieces of the API use

C itself. This part of the book instructs you in the basics of these languages:
• Chapter 1 explains C. In general, you will probably not need to know all the ins
and outs of C, so this chapter restricts itself to those aspects of C that you need to
know in order to use both Objective-C and the C-based areas of the API.
• Objective-C adds object-based programming features to C. Chapter 2 discusses
object-based programming in general architectural terms. It also explains some
extremely important terms that will be used throughout the book, along with the
concepts that lie behind them.
• Chapter 3 introduces the basic syntax of Objective-C.
• Chapter 4 continues the explanation of Objective-C, discussing the nature of
Objective-C classes, with emphasis on how to create a class in code.
• Chapter 5 completes the introduction to Objective-C, discussing how instances
are created and initialized, along with an explanation of such related topics as
polymorphism, instance variables, accessors, self and super, key–value coding,
and properties.
Even at this point, our discussion of Objective-C is not yet complete; we’ll return in
Part III to a description of further aspects of the language: those that are particularly
bound up with the Cocoa frameworks.
www.it-ebooks.info

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×