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

Apress beginning iOS 5 development, exploring the iOS SDK (2011)

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 (13.57 MB, 743 trang )

i
Beginning iOS 5
Development
Exploring the iOS SDK




■ ■ ■
Dave Mark
Jack Nutting
Jeff LaMarche

Beginning iOS 5 Development: Exploring the iOS SDK
Copyright © 2011 by Dave Mark, Jack Nutting, Jeff LaMarche
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or
part of the material is concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way,
and transmission or information storage and retrieval, electronic adaptation, computer software,
or by similar or dissimilar methodology now known or hereafter developed. Exempted from this
legal reservation are brief excerpts in connection with reviews or scholarly analysis or material
supplied specifically for the purpose of being entered and executed on a computer system, for
exclusive use by the purchaser of the work. Duplication of this publication or parts thereof is
permitted only under the provisions of the Copyright Law of the Publisher's location, in its
current version, and permission for use must always be obtained from Springer. Permissions for
use may be obtained through RightsLink at the Copyright Clearance Center. Violations are liable
to prosecution under the respective Copyright Law.
ISBN-13 (pbk): 978-1-4302-3605-4
ISBN-13 (electronic): 978-1-4302-3606-1
Trademarked names, logos, and images may appear in this book. Rather than use a trademark


symbol with every occurrence of a trademarked name, logo, or image we use the names, logos,
and images only in an editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of opinion as to whether or not
they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the authors nor the editors nor the publisher can accept any legal
responsibility for any errors or omissions that may be made. The publisher makes no warranty,
express or implied, with respect to the material contained herein.
President and Publisher: Paul Manning
Lead Editor: Tom Welsh
Technical Reviewer: Mark Dalrymple
Editorial Board: Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Morgan Ertel,
Jonathan Gennick, Jonathan Hassell, Robert Hutchinson, Michelle Lowman,
James Markham, Matthew Moodie, Jeff Olson, Jeffrey Pepper, Douglas Pundick, Ben
Renow-Clarke, Dominic Shakeshaft, Gwenan Spearing, Matt Wade, Tom Welsh
Coordinating Editor: Kelly Moritz
Copy Editor: Marilyn Smith
Compositor: MacPS, LLC
Indexer: BIM Indexing & Proofreading Services
Artist: SPi Global
Cover Designer: Anna Ishchenko
Distributed to the book trade worldwide by Springer Science+Business Media New York, 233
Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail

, or visit
www.springeronline.com
.
For information on translations, please e-mail , or visit www.apress.com.

Apress and friends of ED books may be purchased in bulk for academic, corporate, or
promotional use. eBook versions and licenses are also available for most titles. For more
information, reference our Special Bulk Sales–eBook Licensing web page at
www.apress.com/bulk-sales
.
Any source code or other supplementary materials referenced by the author in this text is
available to readers at www.apress.com. For detailed information about how to locate your book’s
source code, go to www.apress.com/source-code/.
This book is dedicated to the memory of Steve Jobs.
We continue to be inspired by his spirit and his vision.
iv

Contents at a Glance
Contents v
About the Authors xiv
About the Technical Reviewer xv
Acknowledgments xvi
Preface xvii

Chapter 1: Welcome to the Jungle 1

Chapter 2: Appeasing the Tiki Gods 13

Chapter 3: Handling Basic Interaction 45

Chapter 4: More User Interface Fun 69

Chapter 5: Autorotation and Autosizing 113

Chapter 6: Multiview Applications 133


Chapter 7: Tab Bars and Pickers 163

Chapter 8: Introduction to Table Views 217

Chapter 9: Navigation Controllers and Table Views 277

Chapter 10: Storyboards 353

Chapter 11: iPad Considerations 381

Chapter 12: Application Settings and User Defaults 407

Chapter 13: Basic Data Persistence 445

Chapter 14: Hey! You! Get onto iCloud! 493

Chapter 15: Grand Central Dispatch, Background Processing, and You 525

Chapter 16: Drawing with Quartz and OpenGL 563

Chapter 17: Taps, Touches, and Gestures 603

Chapter 18: Where Am I? Finding Your Way with Core Location 633

Chapter 19: Whee! Gyro and Accelerometer! 645

Chapter 20: The Camera and Photo Library 673

Chapter 21: Application Localization 685


Chapter 22: Where to Next? 705
Index 711
v

Contents
Contents at a Glance iv
About the Authors xiv
About the Technical Reviewer xv
Acknowledgments xvi
Preface xvii


Chapter 1: Welcome to the Jungle 1
What This Book Is 1 
What You Need 1 
Developer Options 3 
What You Need to Know 4 
What’s Different About Coding for iOS? 5 
Only One Active Application 6 
Only One Window 6 
Limited Access 6 
Limited Response Time 6 
Limited Screen Size 7 
Limited System Resources 7 
No Garbage Collection, but… 8 
Some New Stuff 8 
A Different Approach 8 
What’s in This Book 9 
What’s New in This Update? 11

Are You Ready? 11

Chapter 2: Appeasing the Tiki Gods 13
Setting Up Your Project in Xcode 13
The Xcode Workspace Window 18
A Closer Look at Our Project 28
Introducing Xcode’s Interface Builder 30
What’s in the Nib File? 32
The Library 33
Adding a Label to the View 34
Changing Attributes 37
■ CONTENTS


vi
Some iPhone Polish—Finishing Touches 39
Bring It on Home 44

Chapter 3: Handling Basic Interaction 45
The Model-View-Controller Paradigm 46
Creating Our Project 47
Looking at the View Controller 48
Understanding Outlets and Actions 49
Cleaning Up the View Controller 51
Designing the User Interface 52
Trying It Out 64
Looking at the Application Delegate 64
Bring It on Home 68

Chapter 4: More User Interface Fun 69

A Screen Full of Controls 69
Active, Static, and Passive Controls 72
Creating the Application 73
Implementing the Image View and Text Fields 74
Adding the Image View 74
Resizing the Image View 77
Setting View Attributes 79
Adding the Text Fields 82
Creating and Connecting Outlets 89
Closing the Keyboard 91
Closing the Keyboard When Done Is Tapped 91
Touching the Background to Close the Keyboard 93
Adding the Slider and Label 95
Creating and Connecting the Actions and Outlets 97
Implementing the Action Method 98
Implementing the Switches, Button, and Segmented Control 98
Implementing the Switch Actions 102
Implementing the Segmented Control Action 105
Implementing the Action Sheet and Alert 105
Conforming to the Action Sheet Delegate Method 106
Showing the Action Sheet 106
Spiffing Up the Button 109
Using the viewDidLoad Method 110
Control States 111
Stretchable Images 111
Crossing the Finish Line 112

Chapter 5: Autorotation and Autosizing 113
The Mechanics of Autorotation 114
Points, Pixels, and the Retina Display 114

Autorotation Approaches 115
Handling Rotation Using Autosize Attributes 115
Configuring Supported Orientations 116
Specifying Rotation Support 117
Designing an Interface with Autosize Attributes 118
■ CONTENTS


vii
Using the Size Inspector’s Autosize Attributes 120
Setting the Buttons’ Autosize Attributes 122
Restructuring a View When Rotated 123
Creating and Connecting Outlets 125
Moving the Buttons on Rotation 125
Swapping Views 126
Designing the Two Views 128
Implementing the Swap 130
Changing Outlet Collections 131
Rotating Out of Here 132

Chapter 6: Multiview Applications 133
Common Types of Multiview Apps 133
The Architecture of a Multiview Application 138
The Root Controller 141
Anatomy of a Content View 142
Building View Switcher 142
Creating Our View Controller and Nib Files 144
Modifying the App Delegate 146
Modifying BIDSwitchViewController.h 148
Adding a View Controller 148

Building a View with a Toolbar 150
Writing the Root View Controller 152
Implementing the Content Views 156 
Animating the Transition 159
Switching Off 161

Chapter 7: Tab Bars and Pickers 163
The Pickers Application 164
Delegates and Data Sources 169
Setting Up the Tab Bar Framework 170
Creating the Files 171
Adding the Root View Controller 172 
Creating TabBarController.xib 173
The Initial Test Run 181
Implementing the Date Picker 182 
Implementing the Single-Component Picker 186
Declaring Outlets and Actions 186
Building the View 187
Implementing the Controller As a Data Source and Delegate 188
Implementing a Multicomponent Picker 192
Declaring Outlets and Actions 193
Building the View 193
Implementing the Controller 194
Implementing Dependent Components 196
Creating a Simple Game with a Custom Picker 203
Writing the Controller Header File 203 
Building the View 204
Adding Image Resources 205
■ CONTENTS



viii
Implementing the Controller 205
Final Details 210
Linking in the Audio Toolbox Framework 214
Final Spin 215

Chapter 8: Introduction to Table Views 217
Table View Basics 218
Table Views and Table View Cells 218
Grouped and Plain Tables 220
Implementing a Simple Table 221
Designing the View 221
Writing the Controller 222
Adding an Image 226
Using Table View Cell Styles 228
Setting the Indent Level 230
Handling Row Selection 231
Changing the Font Size and Row Height 233
Customizing Table View Cells 235
Adding Subviews to the Table View Cell 236
Creating a UITableViewCell Subclass 237
Loading a UITableViewCell from a Nib 242
Grouped and Indexed Sections 248
Building the View 248
Importing the Data 248
Implementing the Controller 249
Adding an Index 254
Implementing a Search Bar 255
Rethinking the Design 255

A Deep Mutable Copy 256
Updating the Controller Header File 258
Modifying the View 259
Modifying the Controller Implementation 264
Putting It All on the Table 276

Chapter 9: Navigation Controllers and Table Views 277
Navigation Controller Basics 277
Stacky Goodness 278
A Stack of Controllers 278
Nav, a Hierarchical Application in Si x Parts 280
Meet the Subcontrollers 280
The Nav Application’s Skeleton 286
Adding the Images to the Project 294
First Subcontroller: The Disclosure Button View 295
Second Subcontroller: The Checklist 304
Third Subcontroller: Controls on Table Rows 310
Fourth Subcontroller: Movable Rows 317
Fifth Subcontroller: Deletable Rows 324
Sixth Subcontroller: An Editable Detail Pane 330
■ CONTENTS


ix
But There’s One More Thing. . . 349
Breaking the Tape 352

Chapter 10: Storyboards 353
Creating a Simple Storyboard 354
Dynamic Prototype Cells 358

Dynamic Table Content, Storyboard-Style 358
Editing Prototype Cells 359
Good Old Table View Data Source 361
Will It Load? 363
Static Cells 364
Going Static 365
So Long, Good Old Table View Data Source 366
You Say Segue, I Say Segue 367
Creating Segue Navigator 368
Filling the Blank Slate 369
First Transition 372
A Slightly More Useful Task List 372 
Viewing Task Details 373
Make More Segues, Please 374
Passing a Task from the List 374 
Handling Task Details 376
Passing Back Details 377
Making the List Receive the Details 378
If Only We Could End with a Smooth Transition 379

Chapter 11: iPad Considerations 381
Split Views and Popovers 381
Creating a SplitView Project 383
The Storyboard Defines the Structure 385
The Code Defines the Functionality 387
Here Come the Presidents 394
Creating Your Own Popover 401
iPad Wrap-Up 406

Chapter 12: Application Settings and User Defaults 407

Getting to Know Your Settings Bundle 407
The AppSettings Application 410
Creating the Project 414
Working with the Settings Bundle 415
Reading Settings in Our Application 431
Registering Default Values 436
Changing Defaults from Our Application 437
Keeping It Real 440
Beam Me Up, Scotty 443

Chapter 13: Basic Data Persistence 445
Your Application’s Sandbox 446
Getting the Documents Directory 447
Getting the tmp Directory 448
File-Saving Strategies 448
■ CONTENTS


x
Single-File Persistence 448
Multiple-File Persistence 449
Using Property Lists 449
Property List Serialization 449
The First Version of the Persistence Application 451
Archiving Model Obj ects 456
Conforming to NSCoding 457
Implementing NSCopying 458
Archiving and Unarchiving Data Objects 459
The Archiving Application 460
Using iOS’s Embedded SQLite3 463

Creating or Opening the Database 464
Using Bind Variables 466
The SQLite3 Application 467
Using Core Data 473
Entities and Managed Objects 475
The Core Data Application 479
Persistence Rewarded 491

Chapter 14: Hey! You! Get onto iCloud! 493
Managing Document Storage with UIDocument 494
Building TinyPix 494
Creating BIDTinyPixDocument 495
Code Master 499
Initial Storyboarding 505
Creating BIDTinyPixView 508
Storyboard Detailing 513
Adding iCloud Support 516
Creating a Provisioning Profile 517
Enabling iCloud Entitlements 518
How to Query 518
Save Where? 520
Storing Preferences on iCloud 521
What We Didn’t Cover 522

Chapter 15: Grand Central Dispatch, Background Processing, and You 525
Grand Central Dispatch 525
Introducing SlowWorker 526
Threading Basics 530
Units of Work 531
GCD: Low-Level Queueing 531

Becoming a Blockhead 532
Improving SlowWorker 533
Background Processing 539
Application Life Cycle 541
State-Change Notifications 541
Creating State Lab 543
Exploring Execution States 544
Making Use of Execution State Changes 546
■ CONTENTS


xi
Handling the Inactive State 547
Handling the Background State 552
Grand Central Dispatch, Over and Out 562

Chapter 16: Drawing with Quartz and OpenGL 563
Two Views of a Graphical World 563
The Quartz 2D Approach to Drawing 564
Quartz 2D’s Graphics Contexts 565
The Coordinate System 566
Specifying Colors 567
Drawing Images in Context 569 
Drawing Shapes: Polygons, Lines, and Curves 569
Quartz 2D Tool Sampler: Patterns, Gradients, and Dash Patterns 570
The QuartzFun Application 572
Setting Up the QuartzFun Application 572
Adding Quartz 2D Drawing Code 584
Optimizing the QuartzFun Application 589
The GLFun Application 592

Setting Up the GLFun Application 593
Creating BIDGLFunView 594
Updating BIDViewController 601
Updating the Nib 602
Finishing GLFun . 602 
Drawing to a Close 602

Chapter 17: Taps, Touches, and Gestures 603
Multitouch Terminology . 604 
The Responder Chain 604
Responding to Events 605
Forwarding an Event: Keeping the Responder Chain Alive 606
The Multitouch Architecture 606
The Four Touch Notification Methods 607
The TouchExplorer Application 608 
The Swipes Application 613
Automatic Gesture Recognition 616
Implementing Multi ple Swipes 618
Detecting Multiple Taps 620 
Detecting Pinches 625
Defining Custom Gestures 627
The CheckPlease Application 628
The CheckPlease Touch Methods 630
Garçon? Check, Please! 632

Chapter 18: Where Am I? Finding Your Way with Core Location 633
The Location Manager 634
Setting the Desired Accuracy 634
Setting the Distance Filter 634
Starting the Location Manager 635

Using the Location Manager Wisely 635
The Location Manager Delegate 635
■ CONTENTS


xii
Getting Location Updates 636
Getting Latitude and Longitude Using CLLocation 636
Error Notifications 638
Trying Out Core Location 639
Updating Location Manager 643
Determining Distance Traveled 644
Wherever You Go, There You Are 644

Chapter 19: Whee! Gyro and Accelerometer! 645
Accelerometer Physics 645
Don’t Forget Rotation 646
Core Motion and the Motion Manager 647
Event-Based Motion 647
Proactive Motion Access 653
Accelerometer Results 655
Detecting Shakes 656
Baked-In Shaking 657
Shake and Break 658
Accelerometer As Directional Controller 664
Rolling Marbles 664
Writing the Ball View 666
Calculating Ball Movement 669
Rolling On 672


Chapter 20: The Camera and Photo Library 673
Using the Image Picker and UIImagePickerController 673
Implementing the Image Picker Controller Delegate 675
Road Testing the Camera and Library 677
Designing the Interface 679
Implementing the Camera View Controller 679
It’s a Snap! 684

Chapter 21: Application Localization 685
Localization Architecture 685
Strings Files 687
What’s in a Strings File? 687
The Localized String Macro 688
Real-World iOS: Localizing Your Application 688
Setting Up LocalizeMe 689
Trying Out LocalizeMe 693
Localizing the Nib 694
Localizing an Image 698
Generating and Localizing a Strings File 701
Localizing the App Display Name 703
Auf Wiedersehen 704

Chapter 22: Where to Next? 705
Apple’s Documentation 705
Mailing Lists 706
Discussion Forums 706
Web Sites 707
■ CONTENTS



xiii
Blogs 708
Conferences 708
Follow the Authors 710
Farewell 710

Index 711

xiv

About the Authors
Dave Mark is a longtime Mac developer and author, who has written a number
of books on Mac and iOS development, including Beginning iPhone 4
Development (Apress, 2011), More iPhone 3 Development (Apress, 2010), Learn
C on the Mac (Apress, 2008), Ultimate Mac Programming (Wiley, 1995), and
The Macintosh Programming Primer series (Addison-Wesley, 1992). Dave was
one of the founders of MartianCraft, an iOS and Android development house.
Dave loves the water and spends as much time as possible on it, in it, or near it.
He lives with his wife and three children in Virginia.


Jack Nutting has been using Cocoa since the olden days, long before it was
even called Cocoa. He has used Cocoa and its predecessors to develop software
for a wide range of industries and applications, including gaming, graphic
design, online digital distribution, telecommunications, finance, publishing,
and travel. When he is not working on Mac or iOS projects, he is developing
web applications with Ruby on Rails. Jack is a passionate proponent of
Objective-C and the Cocoa frameworks. At the drop of a hat, he will speak at
length on the virtues of dynamic dispatch and runtime class manipulations to
anyone who will listen (and even to some who won’t). Jack has written several

books on iOS and Mac development, including Beginning iPhone 4
Development (Apress, 2011), Learn Cocoa on the Mac (Apress, 2010), and Beginning iPad
Development for iPhone Developers (Apress, 2010). He blogs from time to time at
www.nuthole.com.

Jeff LaMarche is a Mac and iOS developer with more than 20 years of
programming experience. Jeff has written a number of iOS and Mac
development books, including Beginning iPhone 4 Development (Apress, 2011),
More iPhone 3 Development (Apress, 2010), and Learn Cocoa on the Mac
(Apress, 2010). Jeff is a principal at MartianCraft, an iOS and Android
development house. He has written about Cocoa and Objective-C for MacTech
Magazine, as well as articles for Apple’s developer web site. Jeff also writes
about iOS development for his widely read blog at
www.iphonedevelopment.blogspot.com.
xv

About the Technical Reviewer
Mark Dalrymple is a longtime Mac and Unix programmer, working on cross-
platform tool kits, Internet publishing tools, high-performance web servers,
and end-user desktop applications. He is also the principal author of Learn
Objective-C on the Mac (Apress, 2009) and Advanced Mac OS X Programming
(Big Nerd Ranch, 2005). In his spare time, Mark plays trombone and bassoon,
and makes balloon animals.

xvi

Acknowledgments
This book could not have been written without our mighty, kind, and clever families, friends, and
cohorts. First and foremost, eternal thanks to Terry, Weronica, and Deneen for putting up with
us, and for keeping the rest of the universe at bay while we toiled away on this book. This project

saw us tucked away in our writers’ cubby for many long hours, and somehow, you didn’t
complain once. We are lucky men.
This book could not have been written without the fine folks at Apress. Clay Andres brought
us to Apress in the first place and carried the first few iterations of this book on his back. Dominic
Shakeshaft and Steve Anglin were the gracious masterminds who dealt with all of our complaints
with a smile on their faces, and somehow found solutions that made sense and made this book
better. Kelly Moritz, our wonderful and gracious coordinating editor, was the irresistible force to
our slowly movable object. Tom Welsh, our developmental editor, helped us with some terrific
feedback along the way. They kept the book on the right track and always pointed in the right
direction. Marilyn Smith, copy editor extraordinaire, you were such a pleasure to work with!
Jeffrey Pepper, Frank McGuckin, Brigid Duffy, and the Apress production team took all these
pieces and somehow made them whole. Dylan Wooters assembled the marketing message and
got it out to the world. To all the folks at Apress, thank you, thank you, thank you!
A very special shout-out to our incredibly talented technical reviewer, Mark Dalrymple. In
addition to providing insightful feedback, Mark tested all the code in this book and helped keep
us on the straight and narrow. Thanks, Mark!
Finally, thanks to our children for their patience while their dads were working so hard. This
book is for you, Maddie, Gwynnie, Ian, Kai, Henrietta, Dorotea, Daniel, Kelley, and Ryan.
xvii

Preface
Hard as it is for us to believe, you now hold in your hands (or see on your screen) the fourth
edition of this book. In the years since we set out on this journey, we’ve poured more blood,
sweat, and tears than we ever imagined into this book, in an attempt to give developers the best
introduction to the fantastic and sometimes surprising world of Cocoa Touch development.
We’ve also had a lot of fun along the way, and we hope that you will, too.
This edition of the book has been rebuilt from the ground up to cover the exciting new
changes Xcode 4 brings to the table. Apple reengineered huge portions of Xcode when
transitioning from Xcode 3 to Xcode 4, and again as it moved to the current version (as of this
writing), Xcode 4.2. We’ve followed suit. Every project in the book has been written from scratch

using the amazing technology built into Xcode 4.2.
And, of course, as the title of this new edition implies, each and every project was designed to
work properly under iOS 5. The iOS SDK has evolved significantly with this latest iOS release. As
you might expect, there are many new changes to the project templates and a lot of new ways to
do the things you’ve always done. And, of course, there’s a lot of new technology to master. We’ve
written entirely new chapters on using both storyboards and iCloud, we’ve covered new
strategies for dealing with table views, and we’ve re-created every example project using the
Automatic Reference Counting (ARC) feature to simplify memory management.
In short, we’ve made this latest edition the biggest, most substantial version of the book so
far. Whether you’re new to iOS development or have been working with it for a while, we think
you’ll like the new material covered by this volume. If you haven’t made it through a previous
edition of this book yet, if you feel a bit fuzzy still, or if you just want to help us out as authors, by
all means, pick up this fourth edition. We do appreciate your support. Be sure to check out the
book’s official community forum at , and drop us a line to let us
know about your amazing new apps. We look forward to seeing you on the forum. Happy coding!

Dave, Jack, and Jeff

-->

×