HAPPY BOOKSGIVING
Use code BOOKSGIVING during checkout to save 40%-55% on books and eBooks. Shop now.
Register your product to gain access to bonus material or receive a coupon.
***This is the updated and corrected edition ofThe iOS 5 Developer's Cookbook.***
The iOS 5 Developer’s Cookbook, Third Edition
Covers iOS 5, Xcode 4.2, Objective-C 2.0’s ARC, LLVM, and more!
In this book, bestselling author and iOS development guru Erica Sadun brings together all the information you need to quickly start building successful iOS apps for iPhone, iPad, and iPod touch. Sadun has thoroughly revised this book to focus on powerful new iOS 5 features, the latest version of Objective-C, and the Xcode 4 development tools.
The iOS 5 Developer’s Cookbook, Third Edition is packed with ready-made code solutions for the iOS 5 development challenges you’re most likely to face, eliminating trial-and-error and helping you build reliable apps from the very beginning. Sadun teaches each new concept and technique through robust code that is easy to reuse and extend. This isn’t just cut-and-paste: Using her examples, Sadun fully explains both the “how” and “why” of effective iOS 5 development.
Sadun’s tested recipes address virtually every major area of iOS development, from user interface design to view controllers, gestures and touch, to networking and security. Every chapter groups related tasks together, so you can jump straight to your solution, without having to identify the right class or framework first. Coverage includes:
The iOS 5 Developer's Cookbook: Building Your First Project
Download the sample pages (includes Chapter 3 and Index)
Preface xxvii
1 Introducing the iOS SDK 1
iOS Developer Programs 1
Online Developer Program 2
Standard Developer Program 2
Developer Enterprise Program 3
Developer University Program 3
Registering 3
Getting Started 3
Downloading the SDK 4
Development Devices 5
Simulator Limitations 6
Tethering 7
Understanding Model Differences 8
Screen Size 9
Camera 9
Audio 10
Telephony 10
Core Location and Core Motion Differences 10
Vibration Support and Proximity 11
Processor Speeds 11
OpenGL ES 11
Platform Limitations 12
Storage Limits 12
Data Access Limits 13
Memory Limits 13
Interaction Limits 16
Energy Limits 16
Application Limits 17
User Behavior Limits 18
SDK Limitations 18
Using the Provisioning Portal 19
Setting Up Your Team 19
Requesting Certificates 20
Registering Devices 20
Registering Application Identifiers 21
Provisioning 22
Putting Together iPhone Projects 23
The iPhone Application Skeleton 25
main.m 26
Application Delegate 28
View Controller 30
A Note about the Sample Code in This Book 31
iOS Application Components 32
Application Folder Hierarchy 32
The Executable 32
The Info.plist File 33
The Icon and Launch Images 34
Interface Builder Files 37
Files Not Found in the Application Bundle 37
IPA Archives 38
Sandboxes 38
Programming Paradigms 39
Object-Oriented Programming 39
Model-View-Controller 40
Summary 48
2 Objective-C Boot Camp 51
The Objective-C Programming Language 51
Classes and Objects 52
Creating Objects 54
Memory Allocation 54
Releasing Memory 55
Understanding Retain Counts with MRR 56
Methods, Messages, and Selectors 57
Undeclared Methods 57
Pointing to Objects 58
Inheriting Methods 59
Declaring Methods 59
Implementing Methods 60
Class Methods 62
Fast Enumeration 63
Class Hierarchy 63
Logging Information 64
Basic Memory Management 66
Managing Memory with MRR 67
Managing Memory with ARC 70
Properties 71
Encapsulation 71
Dot Notation 71
Properties and Memory Management 72
Declaring Properties 73
Creating Custom Getters and Setters 74
Property Qualifiers 76
Key-Value Coding 78
Key-Value Observing 79
MRR and High Retain Counts 79
Other Ways to Create Objects 80
Deallocating Objects 82
Using Blocks 84
Defining Blocks in Your Code 85
Assigning Block References 85
Blocks and Local Variables 87
Blocks and typedef 87
Blocks and Memory Management with MRR 88
Other Uses for Blocks 88
Getting Up to Speed with ARC 88
Property and Variable Qualifiers 89
Reference Cycles 92
Autorelease Pools 94
Opting into and out of ARC 95
Migrating to ARC 95
Disabling ARC across a Target 96
Disabling ARC on a File-by-File Basis 97
Creating an ARC-less Project from Xcode Templates 97
ARC Rules 98
Using ARC with Core Foundation and Toll Free Bridging 99
Casting between Objective-C and Core Foundation 99
Choosing a Bridging Approach 101
Runtime Workarounds 102
Tips and Tricks for Working with ARC 103
Crafting Singletons 103
Categories (Extending Classes) 104
Protocols 106
Defining a Protocol 106
Incorporating a Protocol 107
Adding Callbacks 107
Declaring Optional Callbacks 107
Implementing Optional Callbacks 108
Conforming to a Protocol 108
Foundation Classes 109
Strings 110
Numbers and Dates 115
Collections 117
One More Thing: Message Forwarding 123
Implementing Message Forwarding 123
House Cleaning 125
Super-easy Forwarding 126
Summary 126
3 Building Your First Project 127
Creating New Projects 127
Building Hello World the Template Way 129
Create a New Project 129
Introducing the Xcode Workspace 132
Review the Project 137
Open the iPhone Storyboard 138
Edit the View 140
Run Your Application 141
Using the Simulator 142
Simulator: Behind the Scenes 144
Sharing Simulator Applications 146
The Minimalist Hello World 146
Browsing the SDK APIs 149
Converting Interface Builder Files to Their Objective-C Equivalents 151
Using the Debugger 153
Set a Breakpoint 153
Open the Debugger 154
Inspect the Label 155
Set Another Breakpoint 156
Backtraces 157
Console 158
Add Simple Debug Tracing 158
Memory Management 158
Recipe: Using Instruments to Detect Leaks 159
Recipe: Using Instruments to Monitor Cached Object Allocations 162
Simulating Low-Memory Conditions 163
Analyzing Your Code 165
From Xcode to Device: The Organizer Interface 165
Devices 165
Summary 167
Provisioning Profiles 168
Device Logs 168
Applications 169
Console 169
Screenshots 170
Building for the iOS Device 170
Using a Development Provision 170
Enable a Device 171
Inspect Your Application Identifier 172
Set Your Device and Code Signing Identity 172
Set Your Base and Deployment SDK Targets 173
Compile and Run the Hello World Application 174
Signing Compiled Applications 175
Detecting Simulator Builds with Compile-Time
Checks 175
Performing Runtime Compatibility Checks 175
Pragma Marks 177
Collapsing Methods 178
Preparing for Distribution 178
Locating and Cleaning Builds 178
Using Schemes and Actions 179
Adding Build Configurations 181
About Ad Hoc Distribution 182
Building Ad Hoc Packages 183
Over-the-Air Ad Hoc Distribution 184
Building a Manifest 184
Submitting to the App Store 186
Summary 188
4 Designing Interfaces 191
UIView and UIWindow 191
Views That Display Data 192
Views for Making Choices 193
Controls 193
Tables and Pickers 195
Bars 195
Progress and Activity 196
View Controllers 196
UIViewController 197
UINavigationController 197
UITabBarController 198
Split View Controllers 198
Page View Controller 199
Popover Controllers 199
Table Controllers 199
Address Book Controllers 200
Image Picker 200
Mail Composition 200
Document Interaction Controller 200
GameKit Peer Picker 201
Media Player Controllers 201
View Design Geometry 201
Status Bar 202
Navigation Bars, Toolbars, and Tab Bars 203
Keyboards and Pickers 205
Text Fields 207
The UIScreen Class 207
Building Interfaces 207
Walkthrough: Building Storyboard Interfaces 208
Create a New Project 208
Add More View Controllers 208
Organize Your Views 209
Update Classes 210
Name Your Scenes 211
Edit View Attributes 211
Add Navigation Buttons 211
Add Another Navigation Controller 213
Name the Controllers 213
Tint the Navigation Bars 214
Add a Button 214
Change the Entry Point 215
Add Dismiss Code 215
Run the App 216
Popover Walkthrough 216
Add a Navigation Controller 216
Change the View Controller Class 217
Customize the Popover View 217
Make the Connections 218
Edit the Code 218
Walkthrough: Building an iOS-based Temperature Converter with IB 220
Create a New Project 220
Add Media 221
Interface Builder 221
Add Labels and Views 222
Enable Reorientation 223
Test the Interface 223
Add Outlets and an Action 223
Add the Conversion Method 225
Update the Keyboard Type 225
Connecting the iPad Interface 226
Walkthrough: Building a Converter Interface by Hand 227
Putting the Project Together 230
Walkthrough: Creating, Loading, and Using Hybrid Interfaces 230
Create a New XIB Interface File 231
Add a View and Populate It 231
Tag Your Views 231
Edit the Code 232
Designing for Rotation 233
Enabling Reorientation 233
Autosizing 235
Autosizing Example 237
Evaluating the Autosize Option 238
Moving Views 239
Recipe: Moving Views by Mimicking Templates 240
One More Thing: A Few Great Interface Builder Tips 243
Summary 245
5 Working with View Controllers 247
Developing with Navigation Controllers and Split Views 247
Using Navigation Controllers and Stacks 249
Pushing and Popping View Controllers 249
The Navigation Item Class 250
Modal Presentation 251
Recipe: Building a Simple Two-Item Menu 252
Recipe: Adding a Segmented Control 253
Recipe: Navigating Between View Controllers 255
Recipe: Presenting a Custom Modal
Information View 258
Recipe: Page View Controllers 262
Book Properties 262
Wrapping the Implementation 263
Exploring the Recipe 264
Recipe: Scrubbing Pages in a Page View Controller 269
Recipe: Tab Bars 271
Recipe: Remembering Tab State 275
Recipe: Building Split View Controllers 278
Recipe: Creating Universal Split View/Navigation Apps 282
Recipe: Custom Containers and Segues 284
Transitioning Between View Controllers 290
One More Thing: Interface Builder and Tab
Bar Controllers 291
Summary 292
6 Assembling Views and Animations 295
View Hierarchies 295
Recipe: Recovering a View Hierarchy Tree 297
Recipe: Querying Subviews 298
Managing Subviews 300
Adding Subviews 300
Reordering and Removing Subviews 300
View Callbacks 301
Recipe: Tagging and Retrieving Views 301
Using Tags to Find Views 302
Recipe: Naming Views 303
Associated Objects 304
Using a Name Dictionary 305
View Geometry 308
Frames 309
Transforms 310
Coordinate Systems 310
Recipe: Working with View Frames 311
Adjusting Sizes 312
CGRects and Centers 313
Other Utility Methods 314
Recipe: Randomly Moving a Bounded View 318
Recipe: Transforming Views 319
Display and Interaction Traits 320
UIView Animations 321
Building UIView Animation Transactions 322
Building Animations with Blocks 323
Conditional Animation 324
Recipe: Fading a View In and Out 324
Recipe: Swapping Views 326
Recipe: Flipping Views 327
Recipe: Using Core Animation Transitions 328
Recipe: Bouncing Views as They Appear 329
Recipe: Image View Animations 331
One More Thing: Adding Reflections to Views 332
Summary 335
7 Working with Images 337
Finding and Loading Images 337
Reading Image Data 339
Recipe: Accessing Photos from the iOS Photo Album 342
Working with the Image Picker 342
Recovering Image Edit Information 344
Recipe: Retrieving Images from Asset URLs 347
Recipe: Snapping Photos and Writing Them to the Photo Album 349
Choosing Between Cameras 351
Saving Pictures to the Documents Folder 353
Recipe: E-mailing Pictures 354
Creating Message Contents 354
Presenting the Composition Controller 356
Automating Camera Shots 358
Using a Custom Camera Overlay 358
Recipe: Accessing the AVFoundation Camera 359
Requiring Cameras 360
Querying and Retrieving Cameras 360
Establishing a Camera Session 361
Switching Cameras 363
Camera Previews 364
Laying Out a Camera Preview 364
EXIF 365
Image Geometry 365
Building Camera Helper 367
Recipe: Adding a Core Image Filter 368
Recipe: Core Image Face Detection 370
Extracting Faces 376
Recipe: Working with Bitmap Representations 377
Drawing into a Bitmap Context 378
Applying Image Processing 380
Image Processing Realities 382
Recipe: Sampling a Live Feed 384
Converting to HSB 386
Recipe: Building Thumbnails from Images 387
Taking View-based Screenshots 390
Drawing into PDF Files 390
Creating New Images from Scratch 391
Recipe: Displaying Images in a Scrollable View 392
Creating a Multi-Image Paged Scroll 395
Summary 396
8 Gestures and Touches 397
Touches 397
Phases 398
Touches and Responder Methods 399
Touching Views 399
Multitouch 400
Gesture Recognizers 400
Recipe: Adding a Simple Direct Manipulation Interface 401
Recipe: Adding Pan Gesture Recognizers 402
Recipe: Using Multiple Gesture Recognizers at Once 404
Resolving Gesture Conflicts 407
Recipe: Constraining Movement 408
Recipe: Testing Touches 409
Recipe: Testing Against a Bitmap 411
Recipe: Adding Persistence to Direct Manipulation Interfaces 413
Storing State 413
Recovering State 415
Recipe: Persistence Through Archiving 416
Recipe: Adding Undo Support 418
Creating an Undo Manager 418
Child-View Undo Support 418
Working with Navigation Bars 419
Registering Undos 420
Adding Shake-Controlled Undo Support 422
Add an Action Name for Undo and Redo (Optional) 422
Provide Shake-To-Edit Support 423
Force First Responder 423
Recipe: Drawing Touches Onscreen 424
Recipe: Smoothing Drawings 426
Recipe: Detecting Circles 429
Creating a Custom Gesture Recognizer 433
Recipe: Using Multitouch 435
Retaining Touch Paths 438
One More Thing: Dragging from a Scroll View 440
Summary 443
9 Building and Using Controls 445
The UIControl Class 445
Kinds of Controls 445
Control Events 446
Buttons 448
Adding Buttons in Interface Builder 449
Art 450
Connecting Buttons to Actions 451
Buttons That Are Not Buttons 452
Building Custom Buttons in Xcode 453
Multiline Button Text 455
Adding Animated Elements to Buttons 456
Recipe: Animating Button Responses 456
Recipe: Adding a Slider With a Custom Thumb 458
Customizing UISlider 459
Adding Efficiency 460
Appearance Proxies 460
Recipe: Creating a Twice-Tappable Segmented Control 465
Recipe: Subclassing UIControl 467
Creating UIControls 468
Tracking Touches 468
Dispatching Events 468
Working with Switches and Steppers 471
Recipe: Building a Star Slider 472
Recipe: Building a Touch Wheel 476
Adding a Page Indicator Control 478
Recipe: Creating a Customizable Paged Scroller 481
Building a Toolbar 486
Building Toolbars in Code 487
iOS 5 Toolbar Tips 489
Summary 489
10 Working with Text 491
Recipe: Dismissing a UITextField Keyboard 491
Text Trait Properties 492
Other Text Field Properties 493
Recipe: Adjusting Views Around Keyboards 495
Recipe: Dismissing Text Views with Custom Accessory Views 498
Recipe: Resizing Views with Hardware Keyboards 500
Recipe: Creating a Custom Input View 503
Recipe: Making Text-Input-Aware Views 508
Recipe: Adding Custom Input Views to Non-Text Views 511
Adding Input Clicks 511
Recipe: Building a Better Text Editor 513
Recipe: Text Entry Filtering 516
Recipe: Detecting Text Patterns 518
Rolling Your Own Expressions 518
Enumerating Regular Expressions 519
Data Detectors 520
Adding Built-in Type Detectors 520
Recipe: Detecting Misspelling in a UITextView 522
Searching for Text Strings 523
Recipe: Dumping Fonts 524
Recipe: Adding Custom Fonts to Your App 525
Recipe: Basic Core Text and Attributed Strings 526
Using Pseudo-HTML to Create Attributed Text 532
Recipe: Splitting Core Text into Pages 536
Recipe: Drawing Core Text into PDF 537
Recipe: Drawing into Nonrectangular Paths 539
Recipe: Drawing Text onto Paths 542
Drawing Text onto Bezier Paths 543
Drawing Proportionately 544
Drawing the Glyph 545
One More Thing: Big Phone Text 551
Summary 554
11 Creating and Managing Table Views 555
Introducing UITableView and UITableView Controller 555
Creating the Table 556
Recipe: Implementing a Basic Table 558
Populating a Table 558
Data Source Methods 559
Reusing Cells 560
Responding to User Touches 560
Selection Color 561
Changing a Table’s Background Color 561
Cell Types 562
Recipe: Building Custom Cells in Interface Builder 563
Adding in Custom Selection Traits 565
Alternating Cell Colors 565
Removing Selection Highlights from Cells 566
Creating Grouped Tables 567
Recipe: Remembering Control State for Custom Cells 567
Visualizing Cell Reuse 570
Creating Checked Table Cells 571
Working with Disclosure Accessories 572
Recipe: Table Edits 574
Displaying Remove Controls 575
Dismissing Remove Controls 575
Handling Delete Requests 576
Supporting Undo 576
Swiping Cells 576
Adding Cells 576
Reordering Cells 579
Sorting Tables Algorithmically 580
Recipe: Working with Sections 581
Building Sections 582
Counting Sections and Rows 583
Returning Cells 583
Creating Header Titles 584
Creating a Section Index 584
Delegation with Sections 585
Recipe: Searching Through a Table 586
Creating a Search Display Controller 586
Building the Searchable Data Source Methods 587
Delegate Methods 589
Using a Search-Aware Index 589
Customizing Headers and Footers 591
Recipe: Adding “Pull-to-Refresh” to Your Table 592
Coding a Custom Group Table 595
Creating Grouped Preferences Tables 595
Recipe: Building a Multiwheel Table 597
Creating the UIPickerView 598
Recipe: Using a View-based Picker 601
Recipe: Using the UIDatePicker 603
Creating the Date Picker 603
One More Thing: Formatting Dates 606
Summary 608
12 A Taste of Core Data 611
Introducing Core Data 611
Creating and Editing Model Files 612
Generating Class Files 614
Creating a Core Data Context 615
Adding Objects 616
Querying the Database 618
Detecting Changes 619
Removing Objects 619
Recipe: Using Core Data for a Table Data Source 620
Recipe: Search Tables and Core Data 623
Recipe: Integrating Core Data Table Views with Live Data Edits 625
Recipe: Implementing Undo/Redo Support with Core Data 628
Summary 632
13 Alerting the User 633
Talking Directly to Your User Through Alerts 633
Building Simple Alerts 633
Alert Delegates 634
Displaying the Alert 636
Kinds of Alerts 636
“Please Wait”: Showing Progress to Your User 637
Using UIActivityIndicatorView 638
Using UIProgressView 639
Recipe: No-Button Alerts 639
Building a Floating Progress Monitor 642
Recipe: Creating Modal Alerts with Run Loops 642
Recipe: Using Variadic Arguments with Alert Views 645
Presenting Simple Menus 646
Scrolling Menus 648
Displaying Text in Action Sheets 648
Recipe: Building Custom Overlays 649
Tappable Overlays 650
Recipe: Basic Popovers 650
Recipe: Local Notifications 652
Alert Indicators 654
Badging Applications 654
Recipe: Simple Audio Alerts 654
System Sounds 655
Vibration 656
Alerts 656
Delays 656
One More Thing: Showing the Volume Alert 658
Summary 659
14 Device Capabilities 661
Accessing Basic Device Information 661
Adding Device Capability Restrictions 662
Recipe: Recovering Additional Device Information 664
Monitoring the iPhone Battery State 666
Enabling and Disabling the Proximity Sensor 667
Recipe: Using Acceleration to Locate “Up” 668
Retrieving the Current Accelerometer Angle Synchronously 670
Calculate a Relative Angle 671
Working with Basic Orientation 671
Recipe: Using Acceleration to Move Onscreen Objects 672
Adding a Little Sparkle 675
Recipe: Core Motion Basics 676
Testing for Sensors 677
Handler Blocks 677
Recipe: Retrieving and Using Device Attitude 680
Detecting Shakes Using Motion Events 681
Recipe: Detecting Shakes via the Accelerometer 683
Recipe: Using External Screens 686
Detecting Screens 687
Retrieving Screen Resolutions 687
Setting Up Video Out 688
Adding a Display Link 688
Overscanning Compensation 688
VIDEOkit 688
One More Thing: Checking for Available Disk Space 692
Summary 693
15 Networking 695
Checking Your Network Status 695
Recipe: Extending the UIDevice Class for Reachability 697
Scanning for Connectivity Changes 700
Recovering IP and Host Information 702
Using Queues for Blocking Checks 705
Checking Site Availability 707
Synchronous Downloads 709
Asynchronous Downloads in Theory 713
Recipe: Asynchronous Downloads 715
Handling Authentication Challenges 721
Storing Credentials 722
Recipe: Storing and Retrieving Keychain Credentials 725
Recipe: Uploading Data 728
NSOperationQueue 728
Twitter 732
Recipe: Converting XML into Trees 733
Trees 733
Building a Parse Tree 734
Using the Tree Results 736
Recipe: Building a Simple Web-based Server 738
One More Thing: Using JSON Serialization 742
Summary 742
Index 745