IPhone Programming: the Big Nerd Ranch Guide 9780321706249, 0321706242

Based on Big Nerd Ranch’s popular iPhone Bootcamp class, iPhone Programming: The Big Nerd Ranch Guide leads you through

246 106 10MB

English Pages 415 [352] Year 2010

Report DMCA / Copyright

DOWNLOAD PDF FILE

Table of contents :
Cover......Page 1
Contents......Page 6
Our Teaching Philosophy......Page 12
How This Book Is Organized......Page 13
Style Choices......Page 15
Hardware, Software, and Deployment......Page 16
1. A Simple iPhone Application......Page 18
Creating an Xcode Project......Page 19
Using Interface Builder......Page 20
Model-View-Controller......Page 22
Declaring instance variables......Page 24
Setting pointers......Page 25
Setting targets and actions......Page 27
Implementing Methods......Page 28
Deploying an Application......Page 30
Application Icons......Page 31
Default Images......Page 32
Objects......Page 34
Using Instances......Page 35
Writing the RandomPossessions Tool......Page 37
NSArray and NSMutableArray......Page 39
Subclassing an Objective-C Class......Page 40
Instance variables......Page 42
Accessors and properties......Page 43
Instance methods......Page 44
Initializers......Page 45
Super......Page 46
Initializer chain......Page 47
Class methods......Page 48
Objective-C 2.0 Additions......Page 51
Managing memory in C......Page 54
Managing memory with objects......Page 55
Using retain counts......Page 56
Avoiding memory leaks with autorelease......Page 58
Managing memory in accessors and properties......Page 59
Retain count rules......Page 60
Managing Memory in RandomPossessions......Page 61
Delegation......Page 66
Using frameworks......Page 68
Core Location......Page 69
Receiving updates from CLLocationManager......Page 71
For the More Curious: Compiler and Linker Errors......Page 72
For the More Curious: Protocols......Page 74
Object Diagrams......Page 78
MapKit Framework......Page 79
Interface Properties......Page 80
Being a MapView Delegate......Page 82
Your own MKAnnotation......Page 84
Tagging locations......Page 86
For the More Curious: Renaming an Application......Page 89
Creating a Custom View......Page 92
The drawRect: method......Page 93
Instantiating a UIView......Page 95
Drawing Text and Shadows......Page 96
Using UIScrollView......Page 97
Zooming......Page 98
Hiding the Status Bar......Page 99
For the More Curious: Redrawing Views......Page 100
View Controllers and XIB Files......Page 102
Using View Controllers......Page 103
Creating the UITabBarController......Page 104
Creating view controllers and tab bar items......Page 105
Creating views for the view controllers......Page 108
The Lifecycle of a View Controller......Page 112
Challenge: Map Tab......Page 113
For the More Curious: Paging......Page 114
Setting Up the Accelerometer......Page 116
Getting Accelerometer Data......Page 117
Using Accelerometer Data......Page 118
Detecting Shakes......Page 119
For the More Curious: Filtering and Frequency......Page 121
Notification Center......Page 124
UIDevice Notifications......Page 125
Autorotation......Page 126
For the More Curious: Forcing Landscape Mode......Page 129
For the More Curious: Overriding Autorotation......Page 130
Beginning the Homepwner Application......Page 132
UITableViewController......Page 133
Subclassing UITableViewController......Page 134
UITableView's Data Source......Page 137
UITableViewDataSource protocol......Page 138
UITableViewCells......Page 140
Reusing UITableViewCells......Page 142
Challenge: Sections......Page 144
Editing Mode......Page 146
Deleting Rows......Page 149
Moving Rows......Page 150
Inserting Rows......Page 151
UINavigationController......Page 156
UINavigationBar......Page 160
An Additional UIViewController......Page 162
The XIB File and File's Owner......Page 163
Setting up ItemDetailViewController......Page 164
Navigating with UINavigationController......Page 166
Appearing and disappearing views......Page 169
Challenge: Number Pad......Page 170
ImageCache: a Singleton......Page 172
NSDictionary......Page 173
Singletons......Page 174
Displaying Images and UIImageView......Page 175
Taking pictures and UIImagePickerController......Page 177
Creating and using keys......Page 181
For the More Curious: Recording Video......Page 184
Application Sandbox......Page 188
Archiving......Page 189
Writing to Disk with NSData......Page 194
For the More Curious: Reading and Writing to Disk......Page 196
For the More Curious: The Application Bundle......Page 197
Handling Low-Memory Warnings......Page 200
View controller memory warnings......Page 201
Simulating Low-Memory Warnings......Page 203
16. Subclassing UITableViewCell......Page 204
Creating HomepwnerItemCell......Page 205
Create subviews......Page 206
Layout subviews......Page 207
Using the custom cell......Page 208
Image Manipulation......Page 209
Challenge: Make it Pretty......Page 212
Touch Events......Page 214
Creating the TouchTracker Application......Page 215
Turning Touches Into Lines......Page 218
Instruments......Page 220
The ObjectAlloc Instrument......Page 221
The Sampler Instrument......Page 223
For the More Curious: UIControl......Page 225
Creating a CALayer......Page 228
Layer Content......Page 230
Implicitly Animatable Properties......Page 232
For the More Curious: Layers and Views......Page 234
Challenge: Dynamic Layer Content......Page 237
Animation Objects......Page 238
Spinning the Time with CABasicAnimation......Page 241
Timing functions......Page 243
Animation completion......Page 244
Bouncing the Time with a CAKeyframeAnimation......Page 245
For the More Curious: Presentation and Model Layers......Page 246
Creating the MediaPlayer Application......Page 248
Playing System Sounds......Page 250
Playing Audio Files......Page 253
Playing Movie Files......Page 254
Challenge: Audio Recording......Page 256
Creating the TopSongs Application......Page 258
Setting up the interface......Page 259
Working with NSURLConnection......Page 261
Parsing XML......Page 263
For the More Curious: The Request Body......Page 266
For the More Curious: Credentials......Page 267
The People Picker......Page 268
Additions to Possession Class......Page 271
Address Book Functions......Page 272
For the More Curious: That Other Delegate Method......Page 275
Internationalization using NSLocale......Page 278
Localizing Resources......Page 279
NSLocalizedString and Strings Tables......Page 282
For the More Curious: NSBundle's Role in Internationalization......Page 285
Publishing a Service......Page 286
Browsing for Services......Page 287
TXT Record......Page 290
Socket Connections......Page 292
Settings Bundle......Page 294
Registering defaults......Page 296
Using the defaults......Page 297
Creating the Nayshunz Application......Page 300
Creating the Database......Page 302
Fetching Data......Page 303
Making and Using the Tree......Page 306
Challenge: Custom Objects......Page 308
27. Core Data......Page 310
Creating the Inventory Application......Page 311
Editing the model file......Page 312
AppController......Page 316
LabelSettingViewController......Page 318
LocationListViewController......Page 321
AssetListViewController......Page 325
CountViewController......Page 328
How It All Works......Page 333
Trade-offs of Persistence Mechanisms......Page 334
Challenge 2: Custom NSManagedObject Subclasses......Page 335
Porting existing projects to the iPad......Page 336
New Stuff......Page 339
A......Page 340
C......Page 341
D......Page 342
H......Page 343
K......Page 344
M......Page 345
N......Page 346
P......Page 347
S......Page 348
U......Page 349
X......Page 351
Z......Page 352
Recommend Papers

IPhone Programming: the Big Nerd Ranch Guide
 9780321706249, 0321706242

  • 0 0 1
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

iPhone Programming The Big Nerd Ranch Guide

Joe Conway Aaron Hillegass

iPhone Programming: The Big Nerd Ranch Guide by Joe Conway and Aaron Hillegass Copyright © 2010 Big Nerd Ranch, Inc. All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recoring, or likewise. For information regarding permissions, contact Big Nerd Ranch, Inc. 1963 Hosea L. Williams Drive SE Suite 209 Atlanta, GA 30317 (404) 478-9005 http://www.bignerdranch.com/ [email protected] The 10-gallon hat with propeller logo is a trademark of Big Nerd Ranch, Inc. Exclusive worldwide distribution of the English edition of this book by Pearson Technology Group 800 East 96th Street Indianapolis, IN 46240 USA http://www.informit.com ISBN-13 978-0321706249 ISBN-10 0321706242 First printing May 2010 The authors and publisher have taken care in writing and printing this book but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. App Store, Apple, Bonjour, Cocoa, Cocoa Touch, Finder, Instruments, Interface Builder, iPad, iPhone, iPod, iPod touch, iTunes, iTunes Store, Keychain, Leopard, Mac, Mac OS, Multi-Touch, Objective-C, Quartz, Snow Leopard, and Xcode are trademarks of Apple, Inc., registered in the U.S. and other countries. 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 the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals.

Acknowledgements While our names appear on the cover, many people helped make this book a reality. We would like to take this chance to thank them. • The other instructors who teach the iPhone Bootcamp fed us with a never-ending stream of suggestions and corrections. They are Scott Ritchie, Brian Hardy, and Alex von Below. • Our tireless editor, Susan Loper, took our distracted mumblings and made them into readable prose. • Several technical reviewers helped us find and fix flaws. They are Bill Monk, Mark Miller, Alex Silverman, Jonathan Saggau, and Mikey Ward. • Ellie Volckhausen designed the cover. (The photo is of the bottom bracket of a bicycle frame.) • The amazing team at Pearson Technology Group patiently guided us through the business end of book publishing. The final and most important thanks goes to our students whose questions inspired us to write this book and whose frustrations inspired us to make it clear and comprehensible.

1

This page intentionally left blank

Introduction ...................................................................................................................................... ix Prerequisites ............................................................................................................................. ix Our Teaching Philosophy ............................................................................................................ ix How To Use This Book .............................................................................................................. x How This Book Is Organized ....................................................................................................... x Style Choices ........................................................................................................................... xii Typographical Conventions ....................................................................................................... xiii Hardware, Software, and Deployment ......................................................................................... xiii 1. A Simple iPhone Application .......................................................................................................... 15 Creating an Xcode Project .......................................................................................................... 16 Using Interface Builder .............................................................................................................. 17 Model-View-Controller .............................................................................................................. 19 Declarations ............................................................................................................................. 21 Declaring instance variables ................................................................................................ 21 Declaring methods ............................................................................................................ 22 Making Connections .................................................................................................................. 22 Setting pointers ................................................................................................................ 22 Setting targets and actions .................................................................................................. 24 Summary ......................................................................................................................... 25 Implementing Methods .............................................................................................................. 25 Build and Run on the Simulator .................................................................................................. 27 Event-driven Programming ......................................................................................................... 27 Deploying an Application ........................................................................................................... 27 Application Icons ...................................................................................................................... 28 Default Images ......................................................................................................................... 29 2. Objective-C .................................................................................................................................. 31 Objects .................................................................................................................................... 31 Using Instances ........................................................................................................................ 32 Writing the RandomPossessions Tool ........................................................................................... 34 NSArray and NSMutableArray ............................................................................................ 36 Subclassing an Objective-C Class ................................................................................................ 37 Instance variables ............................................................................................................. 39 Accessors and properties .................................................................................................... 40 Instance methods .............................................................................................................. 41 Initializers ....................................................................................................................... 42 self ................................................................................................................................. 43 super .............................................................................................................................. 43 Initializer chain ................................................................................................................ 44 Class methods .................................................................................................................. 45 Exceptions and the Console Window ........................................................................................... 48 Objective-C 2.0 Additions .......................................................................................................... 48 3. Memory Management .................................................................................................................... 51 Memory Management Concepts .................................................................................................. 51 Managing memory in C ..................................................................................................... 51 Managing memory with objects ........................................................................................... 52 Reference Counting ................................................................................................................... 53 Using retain counts ........................................................................................................... 53 Avoiding memory leaks with autorelease .............................................................................. 55 Managing memory in accessors and properties ....................................................................... 56 Retain count rules ............................................................................................................. 57 Managing Memory in RandomPossessions .................................................................................... 58 4. Delegation and Core Location ......................................................................................................... 63 Delegation ............................................................................................................................... 63 Beginning the Whereami Application ........................................................................................... 65

iii

iPhone Programming

5.

6.

7.

8.

9.

iv

Using frameworks ............................................................................................................. 65 Core Location .................................................................................................................. 66 Receiving updates from CLLocationManager ......................................................................... 68 Releasing Controller Instance Variables ........................................................................................ 69 Challenge: Heading ................................................................................................................... 69 For the More Curious: Compiler and Linker Errors ......................................................................... 69 For the More Curious: Protocols ................................................................................................. 71 MapKit and Text Input .................................................................................................................. 75 Object Diagrams ....................................................................................................................... 75 MapKit Framework ................................................................................................................... 76 Interface Properties ................................................................................................................... 77 Being a MapView Delegate ........................................................................................................ 79 Your own MKAnnotation ................................................................................................... 81 Tagging locations ............................................................................................................. 83 Challenge: Annotation Extras ...................................................................................................... 86 Challenge: Reverse Geocoding .................................................................................................... 86 Challenge: Changing the Map Type ............................................................................................. 86 For the More Curious: Renaming an Application ............................................................................ 86 Subclassing UIView ...................................................................................................................... 89 Creating a Custom View ............................................................................................................ 89 The drawRect: method ....................................................................................................... 90 Instantiating a UIView ....................................................................................................... 92 Drawing Text and Shadows ........................................................................................................ 93 Using UIScrollView .................................................................................................................. 94 Zooming .................................................................................................................................. 95 Hiding the Status Bar ................................................................................................................ 96 Challenge: Colors ..................................................................................................................... 97 For the More Curious: Retain Cycles ........................................................................................... 97 For the More Curious: Redrawing Views ...................................................................................... 97 View Controllers ........................................................................................................................... 99 View Controllers and XIB Files .................................................................................................. 99 Using View Controllers ............................................................................................................ 100 Creating the UITabBarController ....................................................................................... 101 Creating view controllers and tab bar items ......................................................................... 102 Creating views for the view controllers ............................................................................... 105 viewWillAppear: ..................................................................................................................... 109 The Lifecycle of a View Controller ............................................................................................ 109 Challenge: Map Tab ................................................................................................................ 110 For the More Curious: Paging ................................................................................................... 111 The Accelerometer ....................................................................................................................... 113 Setting Up the Accelerometer .................................................................................................... 113 Getting Accelerometer Data ...................................................................................................... 114 Orientation and Scale of Acceleration ......................................................................................... 115 Using Accelerometer Data ........................................................................................................ 115 Smoothing Accelerometer Data ................................................................................................. 116 Detecting Shakes ..................................................................................................................... 116 Challenge: Changing Colors ...................................................................................................... 118 For the More Curious: Filtering and Frequency ............................................................................ 118 Notification and Rotation .............................................................................................................. 121 Notification Center .................................................................................................................. 121 UIDevice Notifications ............................................................................................................. 122 Autorotation ........................................................................................................................... 123 For the More Curious: Forcing Landscape Mode .......................................................................... 126 Challenge: Proximity Notifications ............................................................................................. 127

iPhone Programming For the More Curious: Overriding Autorotation ............................................................................ 10. UITableView and UITableViewController ...................................................................................... Beginning the Homepwner Application ....................................................................................... UITableViewController ............................................................................................................ Subclassing UITableViewController ................................................................................... UITableView's Data Source ...................................................................................................... UITableViewDataSource protocol ...................................................................................... UITableViewCells ................................................................................................................... Reusing UITableViewCells ............................................................................................... Challenge: Sections ................................................................................................................. 11. Editing UITableViews ................................................................................................................ Editing Mode ......................................................................................................................... Deleting Rows ........................................................................................................................ Moving Rows ......................................................................................................................... Inserting Rows ....................................................................................................................... 12. UINavigationController ............................................................................................................... UINavigationController ............................................................................................................ UINavigationBar ............................................................................................................. An Additional UIViewController ............................................................................................... The XIB File and File's Owner .......................................................................................... Setting up ItemDetailViewController .................................................................................. Navigating with UINavigationController ..................................................................................... Appearing and disappearing views ..................................................................................... Challenge: Number Pad ............................................................................................................ 13. Camera and UIImagePickerController ............................................................................................ ImageCache: a Singleton .......................................................................................................... NSDictionary .................................................................................................................. Singletons ...................................................................................................................... Displaying Images and UIImageView ......................................................................................... Taking pictures and UIImagePickerController ...................................................................... Creating and using keys ................................................................................................... Challenge: Removing an Image ................................................................................................. For the More Curious: Recording Video ..................................................................................... 14. Saving and Loading ................................................................................................................... Application Sandbox ................................................................................................................ Archiving ............................................................................................................................... Writing to Disk with NSData .................................................................................................... Challenge: Archiving Wherewasi ............................................................................................... For the More Curious: Reading and Writing to Disk ...................................................................... For the More Curious: The Application Bundle ............................................................................ 15. Low-Memory Warnings .............................................................................................................. Handling Low-Memory Warnings .............................................................................................. View controller memory warnings ..................................................................................... Simulating Low-Memory Warnings ............................................................................................ 16. Subclassing UITableViewCell ...................................................................................................... Creating HomepwnerItemCell ................................................................................................... Create subviews .............................................................................................................. Layout subviews ............................................................................................................. Using the custom cell ...................................................................................................... Image Manipulation ................................................................................................................. Challenge: Accessory Views ..................................................................................................... Challenge: Make it Pretty ......................................................................................................... 17. Multi-Touch, UIResponder, and Using Instruments .......................................................................... Touch Events .........................................................................................................................

127 129 129 130 131 134 135 137 139 141 143 143 146 147 148 153 153 157 159 160 161 163 166 167 169 169 170 171 172 174 178 181 181 185 185 186 191 193 193 194 197 197 198 200 201 202 203 204 205 206 209 209 211 211

v

iPhone Programming

18.

19.

20.

21.

22.

23.

24.

vi

Creating the TouchTracker Application ....................................................................................... Turning Touches Into Lines ...................................................................................................... The Responder Chain .............................................................................................................. Instruments ............................................................................................................................ The ObjectAlloc Instrument .............................................................................................. The Sampler Instrument ................................................................................................... Challenge: Saving and Loading ................................................................................................. Challenge: Circles ................................................................................................................... For the More Curious: UIControl ............................................................................................... Core Animation Layer ................................................................................................................ Creating a CALayer ................................................................................................................ Layer Content ......................................................................................................................... Implicitly Animatable Properties ................................................................................................ For the More Curious: Programmatically Generating Content .......................................................... For the More Curious: Layers and Views .................................................................................... Challenge: Dynamic Layer Content ............................................................................................ Controlling Animation with CAAnimation ..................................................................................... Animation Objects ................................................................................................................... Spinning the Time with CABasicAnimation ................................................................................. Timing functions ............................................................................................................. Animation completion ...................................................................................................... Bouncing the Time with a CAKeyframeAnimation ........................................................................ Challenge: More Animation ...................................................................................................... For the More Curious: Presentation and Model Layers ................................................................... Playing Audio and Video ............................................................................................................ Creating the MediaPlayer Application ......................................................................................... Playing System Sounds ............................................................................................................ Playing Audio Files ................................................................................................................. Playing Movie Files ................................................................................................................ Low-level APIs ....................................................................................................................... Challenge: Audio Recording ..................................................................................................... Web Services ............................................................................................................................ Creating the TopSongs Application ............................................................................................ Setting up the interface .................................................................................................... Fetching Data From a URL ...................................................................................................... Working with NSURLConnection ...................................................................................... Parsing XML .................................................................................................................. For the More Curious: The Request Body ................................................................................... Challenge: More Data .............................................................................................................. For the More Curious: Credentials ............................................................................................. Address Book ........................................................................................................................... The People Picker ................................................................................................................... Additions to Possession Class ................................................................................................... Address Book Functions ........................................................................................................... For the More Curious: That Other Delegate Method ...................................................................... Localization .............................................................................................................................. Internationalization using NSLocale ........................................................................................... Localizing Resources ............................................................................................................... NSLocalizedString and Strings Tables ........................................................................................ Challenge: Another Localization ................................................................................................ For the More Curious: NSBundle's Role in Internationalization ....................................................... Bonjour .................................................................................................................................... Publishing a Service ................................................................................................................ Browsing for Services ..............................................................................................................

212 215 217 217 218 220 222 222 222 225 225 227 229 231 231 234 235 235 238 240 241 242 243 243 245 245 247 250 251 253 253 255 255 256 258 258 260 263 264 264 265 265 268 269 272 275 275 276 279 282 282 283 283 284

iPhone Programming TXT Record ........................................................................................................................... Socket Connections ................................................................................................................. 25. Settings .................................................................................................................................... Settings Bundle ....................................................................................................................... NSUserDefaults ...................................................................................................................... Registering defaults ......................................................................................................... Using the defaults ........................................................................................................... 26. SQLite ..................................................................................................................................... Creating the Nayshunz Application ............................................................................................ Creating the Database .............................................................................................................. Fetching Data ......................................................................................................................... Making and Using the Tree ...................................................................................................... Challenge: Fetching More Data ................................................................................................. Challenge: Custom Objects ....................................................................................................... 27. Core Data ................................................................................................................................. Creating the Inventory Application ............................................................................................. Editing the model file ...................................................................................................... AppController ................................................................................................................. LabelSettingViewController .............................................................................................. LocationListViewController .............................................................................................. AssetListViewController ................................................................................................... CountViewController ....................................................................................................... How It All Works ................................................................................................................... Trade-offs of Persistence Mechanisms ........................................................................................ Challenge 1: Deleting .............................................................................................................. Challenge 2: Custom NSManagedObject Subclasses ...................................................................... 28. Preparing for the iPad ................................................................................................................. Universal Applications ............................................................................................................. Porting existing projects to the iPad ................................................................................... New Stuff .............................................................................................................................. Index ............................................................................................................................................

287 289 291 291 293 293 294 297 297 299 300 303 305 305 307 308 309 313 315 318 322 325 330 331 332 332 333 333 333 336 337

vii

This page intentionally left blank

Introduction An aspiring iPhone developer faces three basic hurdles: • You must learn the Objective-C language. Objective-C is a small and simple extension to the C language. After the first four chapters of this book, you will have a working knowledge of Objective-C. • You must master the big ideas. These include things like memory management techniques, delegation, archiving, and the proper use of view controllers. The big ideas take a few days to understand. When you reach the halfway point of this book, you will understand these big ideas. • You must master the frameworks. The eventual goal is to know how to use every method of every class in every framework on the iPhone. This is a project for a lifetime: there are over 3000 methods and more than 200 classes available for the iPhone. To make things even worse, Apple adds new classes and new methods with every release of the iPhone OS. In this book, you will be introduced to each of the subsystems that make up the iPhone SDK, but we will not study each one deeply. Instead, our goal is get you to the point where you can search and understand Apple's reference documentation. We have used this material many times at our iPhone Development Bootcamp at Big Nerd Ranch. It is well-tested and has helped hundreds of people become iPhone application developers. We sincerely hope that it proves useful to you.

Prerequisites This book assumes that you are already motivated to learn to write iPhone apps. We won't spend any time convincing you that the iPhone is a compelling piece of technology. We also assume that you know the C programming language and something about object-oriented programming. If this is not true, you should probably start with an introductory book on C and Objective-C. We recommend Kochan's Programming in Objective-C.

Our Teaching Philosophy This book is based on our iPhone Development Bootcamp course. It will teach you the essential concepts of iPhone programming. At the same time, you’ll type in a lot of code and build a bunch of applications. By the end of the book, you’ll have knowledge and experience. However, all the knowledge shouldn’t (and, in this book, won’t) come first. That’s sort of the traditional way we’ve all come to know and hate. Instead, we take a learn-while-doing approach. Development concepts and actual coding go together. Here’s what we’ve learned over the years of teaching iPhone programming: • We’ve learned what ideas people must have to get started programming, and we focus on that subset. • We’ve learned that people learn best when these concepts are introduced as they are needed. • We’ve learned that programming knowledge and experience grow best when they grow together. • We’ve learned that “going through the motions” is much more important than it sounds. Many times we’ll ask you to start typing in code before you understand it. We get that you may feel like a trained monkey typing in a bunch of code that you don’t fully grasp. But the best way to learn coding is to find and fix your typos. Far from being a drag, this basic debugging is where you really learn the ins and outs of the code. That’s why we encourage you to type in the code yourself. You could just download it, but copying and pasting is not programming. We want better for you and your skills. What does this mean for you, the reader? To learn this way takes some trust. And we appreciate yours. It also takes patience. As we lead you through these chapters, we will try to keep you comfortable and tell you what’s happening.

ix

How To Use This Book However, there will be times when you’ll have to take our word for it. (If you think this will bug you, keep reading – we’ve got some ideas to help.) Don’t get discouraged if you run across a concept that you don’t understand right away. Remember that we’re intentionally not providing all the knowledge you will ever need all at once. If a concept seems unclear, we will likely discuss it in more detail later when it becomes necessary. And some things that aren’t clear at the beginning will suddenly make sense when you implement them the first (or the twelfth) time. People learn differently. It’s possible that you will love how we hand out concepts on an as-needed basis. It’s also possible that you’ll find it frustrating. In case of the latter, here are some options: 1. Take a deep breath and wait it out. We’ll get there, and so will you. 2. Check the index. We’ll let it slide if you look ahead and read through a more advanced discussion that occurs later in the book. 3. Check the online Apple documentation. This is an essential developer tool, and you’ll want plenty of practice using it. Consult it early and often. 4. If it’s Objective-C or object-oriented programming concepts that are giving you a hard time (or if you think they will), try Kochan's Programming in Objective-C. It’s a great book that presents these concepts in a more traditional way.

How To Use This Book This book is based on the class we teach at Big Nerd Ranch. As such, it was designed to be consumed in a certain manner. Set yourself a reasonable goal, like “I will do one chapter every day.” When you sit down to attack a chapter, find a quiet place where you won't be interrupted for at least an hour. Shut down your email, your Twitter client, and your chat program. This is not a time for multi-tasking; you will need to concentrate. Do the actual programming. You can read through a chapter first, if you'd like. But the real learning comes when you sit down and code as you go. You will not really understand the idea until you have written a program that uses it and, perhaps more importantly, debugged that program. A couple of the exercises require supporting files. For example, the SQLite exercise is a lot more fun if you have some data to browse. Thus, we have made a script that inserts data into a SQLite file. You can download these resources and solutions to the exercises from !""#$%%&&&'()*+,-.-/+0!'012%3145")1+3% )6!1+,6-1*-/22)+*'7)#. There are two types of learning. When you learn about the Civil War, you are simply adding details to a scaffolding of ideas that you already understand. This is what we will call “Easy Learning”. Yes, learning about the Civil War can take a long time, but you are seldom flummoxed by it. Learning iPhone programming, on the other hand, is “Hard Learning,” and you may find yourself quite baffled at times, especially in the first few days. In writing this book, we have tried to create an experience that will ease you over the bumps in the learning curve. Here are two things you can do to make the journey easier: • Find someone who already knows iPhone programming and will answer your questions. In particular, getting your application onto the device the first time is usually very frustrating if you are doing it without the help of an experienced developer. • Get enough sleep. Sleepy people don't remember what they have learned.

How This Book Is Organized In this book, each chapter addresses one or more ideas of iPhone development followed by hands-on practice. For more coding practice, we issue challenges towards the end of each chapter. We encourage you to take on at least

x

How This Book Is Organized some of these. They are excellent for firming up the concepts introduced in the chapter and making you a more confident iPhone programmer. Finally, most chapters conclude with one or two “For the More Curious” sections that explain certain consequences of the concepts that were introduced earlier. Chapter 1 introduces you to iPhone programming as you build and deploy a tiny application. You’ll get your feet wet with Xcode, Interface Builder, and the iPhone simulator along with all the steps for creating projects and files. The chapter includes a discussion of Model-View-Controller and how it relates to iPhone development. Chapters 2 and 3 provide an overview of Objective-C and memory management. Although you won’t create an iPhone application in these two chapters, you will build and debug a tool called RandomPossessions to ground you in these concepts. (You will reuse this tool and its related class in the Homepwner application introduced in Chapter 10.) In Chapters 4 and 5, you will to learn about the Core Location and MapKit frameworks and create a mapping application called Whereami. You will also get plenty of experience with the important design pattern of delegation and working with protocols, frameworks, and object diagrams. Chapters 6 and 7 focus on the iPhone user interface with the Hypnosister and HypnoTime applications. You will get lots of practice working with views and view controllers as well as implementing scrolling, zooming, paging, and navigating between screens. Chapter 8 covers the iPhone’s accelerometer.You will learn how to obtain, filter, and use the data from the accelerometer to handle motion events, including shakes. You will add to the HypnoTime application In Chapter 9, you will create a smaller application named HeavyRotation while learning about !"#$%&'$ notifications and how to implement autorotation in an application. Chapter 10 introduces the largest application in the book – Homepwner. (If you’re over 35, “Homepwner” is not a typo; you can find the definition of “pwn” at &&&'5-(/+.)0")1+/-8'012.) This application keeps a record of your possessions in case of fire or another catastrophe. Homepwner will take nine chapters total to complete. In Chapters 10, 11, and 16, you will get experience developing tables on the iPhone. You will learn about table views, their view controllers, and their data sources. You will learn how to display data in a table, how to allow the user to edit the table, and how to improve the interface. Chapter 12 builds on the navigation experience gained in Chapter 7. You will learn how to use !"()%&*)+&,-.,-+/,00$/ and will give Homepwner a drill-down interface and a navigation bar. In Chapter 13, you’ll learn how to take pictures with the iPhone’s camera and how to display and store images in Homepwner. You’ll use (1#&'+&,-)/2 and !""3)*$4&'5$/.,-+/,00$/. Chapter 14 delves into ways to save and load data. In particular, you will archive data in the Homepwner application using the 9:;1.)+* protocol. Chapter 15 teaches you how to prepare for low-memory warnings and leads you through handling low-memory warnings in Homepwner. In Chapter 17, you’ll take a break from Homepwner and create a drawing application named TouchTracker. You’ll learn how to add multi-touch capability and more about touch events. You’ll also get experience with the first responder and responder chain concepts and more practice with (1#&'+&,-)/2. In addition, you’ll learn about the Instruments application while debugging performance and memory issues in TouchTracker. Chapters 18 and 19 introduce the concepts of layers and the Core Animation framework with a brief return to the HypnoTime application to implement animations. You will learn about implicit and explicit animations and animation objects, like .67)8&'6-&3)+&,- and .69$2:/)3$6-&3)+&,-.

xi

Style Choices Chapter 20 will teach you how to playback audio and video while building an application called MediaPlayer. You will learn about playing audio and video on the iPhone, where to keep these resources, streaming limits, and the low-level audio API. Chapter 21 ventures into the wide world of web services. You will fetch and parse XML data from the iTunes server in an application you create named TopSongs. You’ll use (1!;?+)M0$6//)2 containing instances of (11+/&-*

/+3&,-3

a pointer to another (1>?+)M0$6//)2 containing instances of (11+/&-*

05--,+"B5,3")1+?+.,P

an )+" that holds the index of the current question in the R5,3")1+3 array

R5,3")1+T),4.

a pointer to the !"?+)M0$6//)2 that is then sent the message &-&+. Methods come in two flavors: instance methods and class methods. Instance methods (like &-&+) are sent to instances of the class, and class methods (like )00,') are sent to the class itself, typically either to create new instances of the class or to retrieve some global property of the class. (We will talk more about class and instance methods later.) What do you do with an instance that has been initialized? You send it more messages. Messages have three parts: receiver

a pointer to the object being asked to execute a method

selector

the name of the method to be executed

arguments

the values to be supplied as the parameters to the method

One such message you can send an (1>?+)M0$6//)2 instance is )@@QMN$'+X \/--/8?+3"/+0,A/..E(F,0"$/+1"!,-E(F,0"]M AAAAAAAAAAAA

(How do you know you can send this message? )@@QMN$'+X is a method of (1>?+)M0$6//)2. Sending the )@@QMN$'+X message to an instance of (1>?+)M0$6//)2 will trigger the )@@QMN$'+X method.)

32

Using Instances The )@@QMN$'+X message is an example of a message with one argument. Objective-C methods can take a number of arguments or none at all. The message &-&+, for instance, has no arguments. On the other hand, you can also send the message /$S0)'$QMN$'+8"-;)-*$XE&+LQMN$'+8:/,36//)2X/)-*$X, which takes three arguments (Figure 2.2).

Figure 2.2. Anatomy of a message

Each argument has a label, and each label ends with a colon. One thing that confuses Objective-C beginners is that the name of the message is all of the labels in a selector. For example, )@@QMN$'+X has one label ()@@QMN$'+X) for its one argument. The message /$S0)'$QMN$'+8"-;)-*$XE&+LQMN$'+8:/,36//)2X/)-*$X has three arguments, so it has three labels. In C++ or Java, this method would look like this: /--/8?+3"/+0,'-,#4/0,E(F,0"3?+^/+*,K)"!E(F,0"3T-12C--/8^/+*,U/^/+*,VA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+1"!,-C--/8V AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+1"!,-^/+*,WM

In these languages, it isn't completely obvious what each of the arguments sent to this function are. In Objective-C, however, each argument is paired with the appropriate label: \/--/8?+3"/+0,A-,#4/0,E(F,0"3?+^/+*,$/^/+*, AAAAAAAAAAAAAAAA&)"!E(F,0"3T-12C--/8$/+1"!,-C--/8 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA-/+*,$/+1"!,-^/+*,]M

Objective-C developers learn to appreciate the clarity of having a label for each argument even though it requires a little more typing. For example, you can have two methods /$S0)'$QMN$'+8"-;)-*$XE&+LQMN$'+8:/,36//)2X/)-*$X and /$S0)'$QMN$'+8"-;)-*$X. These methods do not have to be related; they are two distinct messages that you can send to an instance of (1>?+)M0$6//)2. To destroy an object, you send it the message /$0$)8$. \/--/8?+3"/+0,A-,4,/3,]M

This line of code destroys the object pointed to by the /--/8?+3"/+0, variable. (It's actually a bit more complicated than that, and you'll learn about the details of memory management in the next chapter.) It is important to note that although you destroyed the object, the variable /--/8?+3"/+0, still has a value – the address of where the (1>?+)M0$6//)2 instance used to exist. If you send a message to /--/8?+3"/+0,, it will cause a problem because that object no longer exists. However, if /--/8?+3"/+0, is set to +)4, the problem goes away. (+)4 is the zero pointer. C programmers know it as 9HYY. Java programmers know it as +544.) /--/8?+3"/+0,A[A+)4M AAAAAAAAAAAA

Now there is no danger of sending a message to the outdated memory address. Sending a message to +)4 is okay in Objective-C; nothing will happen. In a language like Java, sending messages to +)4 is illegal, so you see this sort of thing a lot:

33

Writing the RandomPossessions Tool

)?+)M0$6//)2? An array is a collection object (also called a container). In the Cocoa Touch frameworks, there are a few collection objects, such as (1#&'+&,-)/2 and (11$+, and each has a slightly different use. An array is an ordered list of objects that are accessed by an index. Other languages might call it a list or a vector. An (16//)2 is immutable, which means you cannot add or remove objects after the array is instantiated. You can, however, access objects within the array. (16//)2's mutable subclass, (1>?+)M0$6//)2, lets you add and remove objects dynamically. In Objective-C, an array does not actually contain the objects that belong to it; instead it holds a pointer (a reference) to each object. When an object is added to an array, AAAA\/--/8A/..E(F,0"$1(F,0"]M

the address of that object in memory is stored inside the array. Arrays can hold any type of Objective-C object. This means primitives and C structures cannot be added to an array. For example, you cannot have an array of )+"s. Also, because arrays only hold a pointer to an object, you can have objects of different types in a single array. This is different from many other compiled languages where an array can only hold objects of its declared type. Note that you cannot add +)4 to an array. If you need to add holes to an array, you must use the (1(?00 object. (1(?00 is an object that represents +)4 and is used specifically for this task. AAAA\/--/8A/..E(F,0"$\9:9544A+544]]M

To retrieve the pointer to an object later, you send the message ,MN$'+6+"-@$FX to the array, AAAA9::"-)+*AL1(F,0"A[A\/--/8A1(F,0"C"?+.,P$a]M

36

Subclassing an Objective-C Class How do you know the order of the objects in an array? When an object is added to an array with the message )@@QMN$'+X, it is added at the end of the array. You can ask an array how many objects it is currently storing by sending it the message ',?-+. This information is important because if you ask for an object from an array at an index that is greater than the number of objects in the array, an exception will be thrown. (Exceptions are very bad; they will most likely ruin your application and cause it to crash.) AAAA)+"A+52(,-E9>)SD&$EGO3)SD&$EI GGGG"7Q?+0$+G!"6'+&%&+2"-@&')+,/D&$EGO)'+&%&+2"-@&')+,/I GGGG"7Q?+0$+G!"K$F+:&$0@GO0,')+&,-K&+0$:&$0@I N @#-1#,-"8AU+1+/"12)0VA-,"/)+WA?SE5"4,"AH?K)+.1&AL&)+.1&M @,+.

In Interface Builder, open the file =/)+K)+.1&'P)( in the Resources group of the Whereami project. Then open the !"R&-@,E instance in this XIB file by double-clicking on the Window object in the doc window.

Interface Properties Drag an >9>)SD&$E onto the window. Then drop a !"K$F+:&$0@ and a !"6'+&%&+2"-@&')+,/D&$E on the >9>)SD&$E. (If you are having trouble finding these objects, use the search box at the bottom of the Library window.) Reposition them and make the outlet connections as shown in Figure 5.3. When connecting the delegate for an object, remember to drag from the object that is delegating to the object that will be the delegate. For example, to set the >9>)SD&$E's delegate, Control-click the >9>)SD&$E to bring up the connection panel and drag to the RL$/$)3&6SS#$0$*)+$ instance.

Figure 5.3. Whereami XIB layout

locationTitleField delegate activityIndicator mapView

delegate

77

Interface Properties Now you're going to change some of the properties of your !"K$F+:&$0@ and !"6'+&%&+2"-@&')+,/D&$E to improve the user interface. When a !"K$F+:&$0@ is activated, a keyboard appears on the screen. (We'll see why this happens later.) The keyboard's appearance is determined by a set of the !"K$F+:&$0@'s properties called !"K$F+"-S?+K/)&+8. For Whereami, the keyboard should display the placeholder text "Enter Location Name" and a blue-tinted Search key. To make these changes, select the !"K$F+:&$0@ to get to its attributes in the Inspector window. Change the values for Placeholder and Return Key to match what is shown in Figure 5.4.

Figure 5.4. UITextField attributes

Wouldn't it be nice if the !"6'+&%&+2"-@&')+,/D&$E hid itself when it's not animating? Select !"6'+&%&+2"-@&')+,/D&$E and check the box labeled Hide When Stopped in the Attributes panel as shown in Figure 5.5 to make this happen.

Figure 5.5. UIActivityIndicator attributes

Save =/)+K)+.1&'P)( and quit Interface Builder.

78

Being a MapView Delegate

Being a MapView Delegate When Whereami launches, the user will be shown a map around the current location and be able to tag the location by entering a name in the !"K$F+:&$0@. Core Location will get the latitude and longitude of the current location and create an object to represent it. RL$/$)3&6SS#$0$*)+$ will then annotate the >9>)SD&$E at that location. In effect, the user will label locations that have been visited for future reference. An >9>)SD&$E knows how to use Core Location to place the user's location on itself; you do not have to use Core Location directly when dealing with this type of object. If you set the 3!1&3H3,-Y10/")1+ property of an >9>)SD&$E to vu:, it will show the location of the user on the map. At the end of )SS0&')+&,-X@&@:&-&8L)-)*$/G8+)/+!S@)+&-*9>)SD&$E with 8$+;$*&,-X)-&3)+$@X to do the zoom. Build and run the application again. When the map figures out where you are in the world, it zooms in on that location.

Your own MKAnnotation Now, you will write a class >)S4,&-+ that conforms to the =tC++1"/")1+ protocol and use instances of it for tagging locations in Whereami. From the File menu in Xcode, select New File.... A window will appear, and on the lefthand side of the window, select Cocoa Touch Class from the iPhone OS section. On the upper-right side, choose Objective-C class. Select NSObject from the pop-up menu and hit the Next button (Figure 5.7).

Figure 5.7. Creating an NSObject subclass

When prompted, name this class =/#61)+"'2 and check the box labeled Also create "MapPoint.h". Click Finish, and the class files for this object will be added to your project (Figure 5.8).

81

Your own MKAnnotation

Figure 5.8. Naming the subclass

While most of the methods declared in the =tC++1"/")1+ protocol are optional, there is one required method – If >)S4,&-+ is to conform to the =tC++1"/")1+ protocol, it must implement that method. (The protocol actually defines ',,/@&-)+$ as a property, so you will as well. Remember from our discussion of accessors that a property is essentially a collection of method declarations.) ',,/@&-)+$.

>96--,+)+&,-D&$E will interact with its /++1"/")1+ object through the methods declared in the =tC++1"/")1+ protocol. However, because a protocol can't declare instance variables, it is up to >)S4,&-+ to store the data that will be returned from the methods declared in the =tC++1"/")1+ protocol. Change =/#61)+"'! to read as follows: `)2#1-"AGT15+./")1+%T15+./")1+'!I m&3S,/+Gi.,/$)S9&+J>)S9&+kLn @)+",-96--,+)+&,-n J GGGG(11+/&-*GO+&+0$I GGGG.)-)*$/8GE&00G/$+?/-G+L$G0)8+GA,?-@G0,')+&,-G,AG+L$G GGGGJJG@$%&'$GA&/8+gG2,?G@,-j+GE)-+G+L)+G@)+)G&-G+L&8G')8$k GGGGJJG"AG+L&8G0,')+&,-GE)8G3)@$GE)8G3,/$G+L)-GpG3&-?+$8G)*,gG&*-,/$G&+kG GGGG&AGV+GiGUbveWGY GGGGGGGGJJGKL&8G&8G')'L$@G@)+)gG2,?G@,-j+GE)-+G&+gG5$$SG0,,5&-* GGGGGGGG/$+?/-I GGGGd GGGG>)S4,&-+GO3SG\GZZ>)S4,&-+G)00,'[G GGGGGGGGGGGGGGGGGGGGGGGG&-&+R&+L.,,/@&-)+$XZ-$E)S4,&-+ on the map.

Challenge: Changing the Map Type Add a !"1$*3$-+$@.,-+/,0 to the interface. Have this segmented control switch the >9>)SD&$E between the standard, satellite, and hybrid maps.

For the More Curious: Renaming an Application When you create an application, you give it a name. But you aren't stuck with that name for life, and there are at least a couple of reasons you might want to change it. You can change your mind. Usually when I'm working on a new application, I come up with a totally cool name. I show all of my friends every time I see them and talk non-stop about how "SupercoolApp" is going to be so great. When I finish the application, however, I look at the name and think, "That's a really stupid name." Or you can be too late. Once in a blue moon, I write an application and still love the name when I'm finished. (Baaahlast, for example, still makes me laugh when I see it.) Then reality hits, and I find out someone else has already used the name! Whereami is one of those applications. Another iPhone book has a Whereami application example, so our (way cooler) application needs a name change. How does Wherewasi sound? To change the name of an application, choose Edit Active Target from the Project menu. You've been here before, but this time select the Build tab at the top of the window. Select All Configurations from the Configuration: popup button. While there are many groups in the table (and each contains plenty of settings for the target), you are looking for the Packaging group. Find the Product Name setting within that group and double-click on that row (Figure 5.10).

86

For the More Curious: Renaming an Application

Figure 5.10. Renaming an application

A sheet will drop down. Enter Wherewasi into this box and hit OK. Build and run your application again. Check out the name of the application on the home screen now.

87

This page intentionally left blank

Chapter 6. Subclassing UIView In previous chapters, you've created several views: a !"7?++,-, a !"w4"GOGqkegGts1WI GGGGGGGG.B.,-+$F+1+/,5$4)+LV',-+$F+WI GGGGd N

Notice that you are passed a ;d^,0" structure. This is the rectangle that needs to be redrawn, sometimes called a dirty rectangle. Typically, you ignore the dirty rectangle and issue the drawing instructions as though the entire view needed to be redrawn. If, however, your drawing code is particularly intricate, you might be more careful and only redraw the parts in the dirty rectangle to speed up drawing. A ;d^,0" structure (Figure 6.4) contains the members 1-)*)+ and 3)7,. These two members are also structures. The 1-)*)+ is of type ;d61)+" and contains two more