CYAN YELLOW SSSPPPOOOTTT GGGlllooossssss MAGENTA BLACK PANTONE 123 C SSSSPPPPOOOOTTTT MMMMaaaatttteeete BOOKS FOR PROFESSIONALS BY PROFESSIONALS® Companion eBook Available S E TL Apple’s iPhone and iPad are incredibly popular and desirable devices, and Get started building your very own TI Learn how to build Java-based BlackBerry D part of the reason for their popularity is the wonderful assortment of apps i ATE available for Apple’s iTunes App Store. So how do you go about creating your P apipPlhicoanteio annsd f rioPmad s acpraptsch EL own apps for the App Store? If you’ve ever dreamed of the perfect iPhone or h R iPad app but never thought you could write your own, then open this book o and get started! iPhone and iPad Apps for Absolute Beginners will teach you to: n • set up your computer for iPhone and iPad application development e • make small changes to existing apps before creating your own a custom apps n • d give your applications style – making them enjoyable to use and easy to navigate i P • take advantage of numerous Apple innovations, such as the multi- a touch screen and accelerometer d • use shortcuts and cheat sheets to create powerful apps the easy way A With reasonable commitment and computer savvy, anybody – from the absolute p beginner on up – can create simple applications for the iPhone and iPad, and this p book will show you how. Dr. Rory Lewis walks you through the steps required s to getting your first applications up and running. His style of presentation cuts through the fog of jargon and misinformation that surrounds iPhone/iPad appli- f o cation development, and he provides simple, step-by-step instructions, comple- r mented by a plentiful array of detailed screenshots and illustrations, practical ex- A amples, and accompanying online videos that enable you to follow along. b The iPhone is the hottest gadget of this generation, and with the release of s the iPad, Apple has done it again! This larger and more powerful multi-touch, o multi-task wonder device advances the innovative design and functionality of l the iPhone, putting users more naturally and vividly in the driver seat of their u own creative processes. This book is the guide to the fundamentals of iPhone t iPhone iPad Apps and iPad application development in a language anyone can understand, es- e and for pecially dreamers. B e g Absolute Beginners i n n e r s L Dr. Rory Lewis e w COMPANION eBOOK SEE LAST PAGE FOR DETAILS ON $10 eBOOK VERSION ISBN 978-1-4302-2700-7 i Foreword by Ben Easton s 52999 US $29.99 Shelve in Mobile Computing SOURCE CODE ONLINE User level: www.apress.com Beginner 9 781430 227007 this print for content only—size & color not accurate Trim: 7.5 x 9.25 spine = 0.75" 336 page count iPhone and iPad Apps for Absolute Beginners ■ ■ ■ Dr. Rory Lewis i iPhone and iPad Apps for Absolute Beginners Copyright © 2010 by Dr. Rory Lewis All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN-13 (pbk): 978-1-4302-2700-7 ISBN-13 (electronic): 978-1-4302-2701-4 Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1 Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. President and Publisher: Paul Manning Lead Editor: Ben Renow-Clark Technical Reviewer: Kristian Besley Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Jonathan Gennick, Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan Parkes, Jeffrey Pepper, Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh Coordinating Editors: Fran Parnell and Debra Kelly Copy Editor: Jim Compton Compositor: MacPS, LLC Indexer: Potomac Indexing, LLC Artist: April Milne Cover Designer: Anna Ishchenko Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e- mail [email protected], or visit www.springeronline.com. For information on translations, please e-mail [email protected], 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/info/bulksales. The information in this book is distributed on an “as is” basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work. The source code for this book is available to readers at www.apress.com. ii Contents at a Glance ■Contents at a Glance.......................................................................................iv ■Contents..........................................................................................................v ■Foreword: About the Author...........................................................................ix ■About the Contributing Authors.....................................................................xii(cid:1) ■About the Technical Reviewer......................................................................xiii ■Acknowledgments.........................................................................................xiv ■Preface...........................................................................................................xv ■Chapter 1: Before We Get Started....................................................................1 ■Chapter 2: Blast-Off!......................................................................................17 ■Chapter 3: What’s Next?................................................................................53 ■Chapter 4: An Introduction to the Code.........................................................71 ■Chapter 5: Buttons & Labels with Multiple Graphics.....................................93 ■Chapter 6: Switch View with Multiple Graphics..........................................125 ■Chapter 7: Dragging, Rotating, and Scaling................................................209 ■Chapter 8: Table Views, Navigation, and Arrays.........................................235 ■Chapter 9: MapKit........................................................................................261 ■Index............................................................................................................313 iv Contents ■Contents at a Glance.......................................................................................iv(cid:1) ■Contents..........................................................................................................v(cid:1) ■Foreword: About the Author...........................................................................ix ■About the Contributing Authors.....................................................................xii(cid:1) ■About the Technical Reviewer......................................................................xiii(cid:1) ■Acknowledgments.........................................................................................xiv ■Preface...........................................................................................................xv(cid:1) ■Chapter 1: Before We Get Started....................................................................1 Necessities and Accessories..................................................................................................................................1 What I Won’t Teach You..........................................................................................................................................6 Computer Science: A Broad and Diverse Landscape.........................................................................................6 What You Will Learn................................................................................................................................................9 How Does This All Work?......................................................................................................................................10 Our Road Map: Using Xcode and Interface Builder..........................................................................................12 ■Chapter 2: Blast-Off!......................................................................................17 helloWorld_002 – a Navigation-based Application...............................................................................................38 helloWorld_003 – Modifying a Navigation-based App..........................................................................................48 ■Chapter 3: What’s Next?................................................................................53 §I: THE ROAD AHEAD.............................................................................................................................................54 Introducing Chapter 4—An Introduction to the Code......................................................................................54 Introducing Chapter 5—Buttons & Labels with Multiple Graphics..................................................................55 Introducing Chapter 6—Switch View with Multiple Graphics..........................................................................56 Introducing Chapter 7—Dragging, Rotating, and Scaling...............................................................................58 Introducing Chapter 8—Table Views, Navigation, and Arrays.........................................................................59 Introducing Chapter 9—MapKit.......................................................................................................................60 §II: THE iPHONE AND THE iPAD.............................................................................................................................60 §III: A LOOK UNDER THE HOOD..............................................................................................................................66 You’ve Said “Hello!” … but now, INDIO!.........................................................................................................67(cid:1) v ■ CONTENTS ■Chapter 4: An Introduction to the Code.........................................................71 004_helloWorld: Buttons with Graphics................................................................................................................72 Digging the Code...................................................................................................................................................89 Nibs, Zibs, and Xibs.........................................................................................................................................89 Methods...........................................................................................................................................................90 ■Chapter 5: Buttons & Labels with Multiple Graphics.....................................93 helloWorld_005: a View-Based Application..........................................................................................................93 Preliminaries....................................................................................................................................................94 Xcode – Beginning a New Project....................................................................................................................97 Understanding IBOutlets..................................................................................................................................99 Pointers..........................................................................................................................................................101 Properties: Management & Control................................................................................................................103 Adding IBActions............................................................................................................................................105 Coding the Implementation File.....................................................................................................................106 Providing for Synthesis..................................................................................................................................108 Interface Builder: Making the Connections....................................................................................................110 Final Step: File’s Owner & uiImageView........................................................................................................118 Digging the Code.................................................................................................................................................122 IBOutlets and IBActions.................................................................................................................................122 More About Pointers......................................................................................................................................123 In the Chapter Ahead..........................................................................................................................................124 ■Chapter 6: Switch View with Multiple Graphics..........................................125 einSwitch_001—a Window-Based Application..................................................................................................128 Preliminaries..................................................................................................................................................128 Name your Project “einSwitch01”.................................................................................................................133 Create the 1st UIViewController Subclass.....................................................................................................137 Create the Ein1Controller...............................................................................................................................138 Check Header and Implementation Files.......................................................................................................139 Create the Ein2Controller...............................................................................................................................139 Make Sure Images Are Embedded.................................................................................................................140 Save Einstein2View.xib..................................................................................................................................141 Drag the Images into Xcode...........................................................................................................................142 Assign your Icon in the “plist”.......................................................................................................................143 Code the AppViewDelegate............................................................................................................................144 Working SwitchView......................................................................................................................................146 SwitchViewController and AppDelegate........................................................................................................148 SwitchViewController Header File.................................................................................................................152 Ready for Lazy Load—Implementation File...................................................................................................155 A Note about Comments and Lazy Loads......................................................................................................156 Copy Contents of SwitchViewController.txt...................................................................................................158 A Note about Apple’s Boilerplate Implementation File...................................................................................159 Working on the .xib Files...............................................................................................................................161 Select the File’s Owner..................................................................................................................................163 vi ■ CONTENTS Drag a View onto the Screen.........................................................................................................................163 Start Working on the Einstein#View.xib Files................................................................................................167 Repeat Process for Second Image.................................................................................................................171 einSwitch_002—a Tab-Bar Application.............................................................................................................176 einSwitch_003—a Window-Based Application..................................................................................................191 Digging … Your Brain.........................................................................................................................................207 ■Chapter 7: Dragging, Rotating, and Scaling................................................209 DragRotateAndScale—a View-Based Application..............................................................................................210 Preliminaries..................................................................................................................................................211 Starting the DragRotateAndScale App...........................................................................................................211 Creating a Custom UIImageView Subclass....................................................................................................213 Overriding – initWithImage in TransformView.m...........................................................................................215 Creating Touch-Handling Stubs.....................................................................................................................216 Translating in touchesMoved.........................................................................................................................218 Making Use of TransformView.......................................................................................................................220 Creating a TransformView.............................................................................................................................220 Preparing TransformView for Rotation and Scaling.......................................................................................225 Helper Methods..............................................................................................................................................226 Adding to “-touchesBegan”...........................................................................................................................227 Modifying -touchesMoved.............................................................................................................................229 Digging the Code.................................................................................................................................................232 ■Chapter 8: Table Views, Navigation, and Arrays.........................................235 How Shall We Proceed?......................................................................................................................................238 Table Views and Navigation Stacks....................................................................................................................238 Food: Following the App Store Model.................................................................................................................239 Starting the Food App....................................................................................................................................239 Adding the Category Names Array in RootViewController.h..........................................................................241 Creating the Categories Array in -viewDidLoad............................................................................................242 Setting Up Table View Data Source Methods................................................................................................243 Table View Delegation...................................................................................................................................244 Setting up FoodTableViewController..............................................................................................................245 Creating the Convenience Constructor for the FoodTableViewController......................................................248 Data Source and Delegation for the FoodTableViewController......................................................................249 Creating the FoodViewController Class..........................................................................................................250 The FoodViewController Header File..............................................................................................................251 The FoodViewController Convenience Constructor........................................................................................252 Setting Up FoodViewController, -viewDidLoad, and the (.xib).......................................................................252 Icon File.........................................................................................................................................................254 Testing the App..............................................................................................................................................255 Digging the Code.................................................................................................................................................257 Memory Management....................................................................................................................................257 Reuse Identifiers............................................................................................................................................259 ■Chapter 9: MapKit........................................................................................261 vii ■ CONTENTS A Little about Frameworks..................................................................................................................................262 Important Things to Know...................................................................................................................................263 Preinstalled MapKit Apps....................................................................................................................................263 Find Locations................................................................................................................................................264 Get Directions................................................................................................................................................265 See Which Way You’re Facing.......................................................................................................................266 See Traffic......................................................................................................................................................267 Search for a Location.....................................................................................................................................268 Cool and Popular MapKit Apps to Inspire You.....................................................................................................270 MapKit_01: A View-Based Application................................................................................................................271 Possible Prepping for the App........................................................................................................................271 Preliminaries.......................................................................................................................................................273 A New View-Based Template..............................................................................................................................273 Adding the Annotation File.............................................................................................................................274 It’s Already Working!......................................................................................................................................275 Check It Out—the iPad Simulator..................................................................................................................276 Make It Look a Little Bit Better......................................................................................................................277 Dealing with the Implementation...................................................................................................................278 Coding the myPos.h File................................................................................................................................284 The myPos.m File...........................................................................................................................................285 The AppDelegate Files...................................................................................................................................286 Connect MapView with MKMapView.............................................................................................................287 Digging My Students’ MapKit Code....................................................................................................................290 Parsing to MapKit from the Internet...............................................................................................................290 MapKit Parsing...............................................................................................................................................293 Three MapKit Final Projects: CS-201 iPhone Apps, Objective-C................................................................295 Zoom Out … Seeing the Big Picture...................................................................................................................310(cid:1) ■Index............................................................................................................313 viii Foreword: About the Author "Rory and I met in L.A. in 1983. He reminds me of one of my favorite film characters, Buckaroo Banzai—always going in six directions at once. If you stop him and ask what he's doing, he'll answer comprehensively and with amazing detail. Disciplined, colorful, and friendly, he has the uncanny ability to explain the highly abstract in simple, organic terms. He always accomplishes what he sets out to do, and he'll help you do the same. Why you’ll relate to Dr. Lewis While attending Syracuse University as a computer-engineering student, Rory scrambled to pass his classes and make money to support his wife and two young daughters. In 1990, he landed a choice on- campus job as a proctor in the computer labs in the LC Smith College of Engineering. Even though he was struggling with subjects in the Electrical Engineering program, he was always there at the Help Desk. It was a daunting experience for Rory because his job was only to help his fellow students with computer lab equipment questions, but he invariably found his classmates asking deeper and harder questions: “Dude, did you understand the calculus assignment? Can you help me?!” These students assumed that, because Rory was the proctor, he knew the answers. Afraid and full of self-doubt, he sought a way to help them without revealing his inadequacies. Rory learned to start with: “Let’s go back to the basics. Remember that last week the professor presented us with an equation…?” By going back to the fundamentals, restating and rebranding them, Rory began to develop a technique that would, more often than not, lead to working solutions. By the time his senior year rolled around, there was often a line of students waiting at the Help Desk on the nights Rory worked. Fast-Forward 17 Years Picture a long-haired, wacky professor walking through the campus of the University of Colorado at Colorado Springs, dressed in a stunning contrast of old-school and drop-out. As he walks into the Engineering Building, he is greeted by students and faculty who smile and say hearty hellos, all the while probably shaking their heads at his tweed jacket, Grateful Dead t-shirt, khaki pants, and flip flops. As he walks down the hall of the Computer Science Department, there’s a line of students standing outside his office. Reminiscent of the line of students that waited for him at the Help Desk in those early years as a proctor in the computer lab, they turn and greet him, “Good morning, Dr. Lewis!” Many of these students at UC-Colorado Springs are not even in his class, but they know that Dr. Lewis will see them and help them anyway. ix ■ FOREWORD: ABOUT THE AUTHOR Past—Present—Future Dr. Lewis holds three academic degrees. He earned a Bachelor of Science in Computer Engineering from Syracuse University. Syracuse’s LC Smith College of Engineering is one of the country’s top schools. It is there that Intel, AMD, and Microsoft send their top employees to study for their PhDs. Upon completing his BS (with emphasis on the mathematics of electronic circuitry in microprocessors), he went across the quad to the Syracuse University School of Law. During his first summer at law school, Fulbright & Jaworski, the nation’s most prolific law firm, recruited Rory to work in its Austin office, where some of the attorneys specialize in high-tech intellectual- property patent litigation. As part of his clerking experience, Lewis worked on the infamous AMD v. Intel case; he helped assess the algorithms of the mathematics of microprocessor electrical circuitry for the senior partners. During his second summer in law school, Skjerven, Morrill, MacPherson, Franklin, & Friel—the other firm sharing the work on the AMD v. Intel case—recruited Rory to work with them at their Silicon Valley branches (San Jose and San Francisco). After immersing himself in law for several years and receiving his JD at Syracuse, Lewis realized his passion was for the mathematics of computers, not the legal ramifications of hardware and software. He preferred a learning and creative environment rather than the fighting and arguing intrinsic in law. After three years away from academia, Rory Lewis moved south to pursue his PhD in Computer Science at the University of North Carolina at Charlotte. There, he studied under Dr. Zbigniew W. Ras, known worldwide for his innovations in data mining algorithms and methods, distributed data mining, ontologies, and multimedia databases. While studying for his PhD, Lewis taught computer science courses to computer engineering undergraduates, as well as e-commerce and programming courses to MBA students. Upon receiving his PhD in Computer Science, Rory accepted a tenure-track position in Computer Science at the University of Colorado at Colorado Springs, where his research is in the computational mathematics of neurosciences. Most recently, he co-wrote a grant proposal on the mathematical analysis of the genesis of epilepsy with respect to the hypothalamus. However, with the advent of Apple’s revolutionary iPhone and its uniquely flexible platform—and market— for mini-applications, games, and personal computing tools, he grew excited and began experimenting and programming for his own pleasure. Once his own fluency was established, Lewis figured he could teach a class on iPhone apps that would include non-engineers. With his insider knowledge as an iPhone beta tester, he began to integrate the parameters of the proposed iPad platform into his lesson plans—even before the official release in April 2010. The class was a resounding success and the feedback was overwhelmingly positive, from students and colleagues alike. When approached about the prospect of converting his course into a book to be published by Apress, Dr. Lewis jumped at the opportunity. He happily accepted an offer to convert his course outlines, class notes, and videos into the book you are now holding in your hands. Why Write This Book? The reasons Dr. Lewis wrote this book are the same reasons he originally decided to create a class for both engineering and non-engineering majors: the challenge and the fun! According to Lewis, the iPhone and iPad are “...some of the coolest, most powerful, and most technologically advanced tools ever made—period!” He is fascinated by the fact that, just under the appealing touch screen of high-resolution images and fun little icons, the iPhone and iPad are programmed in Objective-C, an incredibly difficult and advanced language. More and more, Lewis was approached by students and colleagues who wanted to program apps for the iPhone and would ask his opinion on their ideas. It seemed that, x
Description: