Preface

This is the iOS Cookbook you’ve been waiting for!

Last year, when iOS 4 debuted, my editor and I had a hard decision to make: Publish the book on iOS 4 and don’t include Xcode 4 material, or hold off until Apple released Xcode 4. We chose to hold off for Xcode 4, feeling that many people would expect to see it covered in the book. What we couldn’t anticipate, however, is that Apple’s NDA would last until Spring 2011, and we knew iOS 5 was right around the corner.

Stuck between a rock and an iOS release, we decided to update the book to iOS 4.3 and to release that as an ebook-only version (that is, we aren’t planning to print that edition—ever). The reason for doing an electronic-only edition on iOS 4.3 was so developers who wanted that info could still have access to it. Once that update was finished and iOS 5 was introduced at WWDC, I quickly turned my attention to updating—and expanding—the cookbook for iOS 5. This is the version you’re currently reading. Finally!

This edition, The iOS 5 Developer’s Cookbook, carries through with the promise of the subtitle: Core Concepts and Essential Recipes for iOS Programmers. That means this book covers what you need to know to get started. For someone who’s just starting out as an iOS developer, this is the ideal book because it covers the tools (Xcode and Interface Builder), the language (Objective-C), and the basic elements common to pretty much every iOS app out there (table views, custom controls, split views, and the like).

But we’re not stopping there. Mid-October 2011 is our cutoff date for getting the book to production this year. While the book is in production, I’ll continue writing and adding more advanced material to The iOS 5 Developer’s Cookbook, along with a bunch of new chapters that won’t make it to print.

Our plan is to combine all this material to create The iOS 5 Developer’s Cookbook: Expanded Electronic Edition, which will release in electronic-only form (namely, ePub for iBooks, Kindle, and PDF for desktops). The Expanded Electronic Edition will include the equivalent of what would amount to several hundred pages of printed material. For customers who have already purchased the ebook form of the print book and only want the additional chapters, we have created The iOS 5 Developer’s Cookbook: The Additional Recipes. As with the Extended Electronic Edition, The Additional Recipes will be available in ePub, Kindle, and PDF.

As in the past, sample code can be found at github. The repository for this Cookbook is located at https://github.com/erica/iOS-5-Cookbook, all of it written after WWDC 2011 and during the time when Apple was routing iOS 5 betas to developers.

If you have suggestions, bug fixes, corrections, or anything else you’d like to contribute to a future edition, please contact me at [email protected]. Let me thank you all in advance. I appreciate all feedback that helps make this a better, stronger book.

—Erica Sadun, November 2011 (updated December 2011)

What You’ll Need

It goes without saying that, if you’re planning to build iOS applications, you’re going to need at least one of those iOS devices to test out your application, preferably a 3GS or later, a third-gen iPod touch or later, or any iPad. The following list covers the basics of what you need to begin:

Apple’s iOS SDK—The latest version of the iOS SDK can be downloaded from Apple’s iOS Dev Center (developer.apple.com/ios). If you plan to sell apps through the App Store, you will need to become a paid iOS developer, which costs $99/year for individuals and $299/year for enterprise (that is, corporate) developers. Registered developers receive certificates that allow them to “sign” and download their applications to their iPhone/iPod touch for testing and debugging.


Apple also offers a University Program for students and educators. If you are a CS student taking classes at the university level, check with your professor to see whether your school is part of the University Program. For more information about the iPhone Developer University Program, see http://developer.apple.com/support/iphone/university.


An Intel-based Mac running Mac OS X Snow Leopard (v 10.6) or Lion (v 10.7)—You need plenty of disk space for development, and your Mac should have at least 1GB RAM, preferably 2GB or 4GB to help speed up compile time.

An iOS device—Although the iOS SDK and Xcode include a simulator for you to test your applications in, you really do need to have an iPhone, iPad, and/or iPod touch if you’re going to develop for the platform. You can use the USB cable to tether your unit to the computer and install the software you’ve built. For real-life App Store deployment, it helps to have several units on hand, representing the various hardware and firmware generations, so you can test on the same platforms your target audience will use.

At least one available USB 2.0 port—This enables you to tether a development iPhone or iPod touch to your computer for file transfer and testing.

An Internet connection—This connection enables you to test your programs with a live Wi-Fi connection as well as with an EDGE or 3G service.

Familiarity with Objective-C—To program for the iPhone, you need to know Objective-C 2.0. The language is based on ANSI C with object-oriented extensions, which means you also need to know a bit of C too. If you have programmed with Java or C++ and are familiar with C, making the move to Objective-C is pretty easy. Chapter 2, “Objective-C Boot Camp,” helps you get up to speed.

Your Roadmap to Mac/iOS Development

As mentioned earlier, one book can’t be everything to everyone. And try as I might, if we were to pack everything you’d need to know into this book, you wouldn’t be able to pick it up. (As it stands, this book offers an excellent tool for upper body development. Please don’t sue us if you strain yourself lifting it.) There is, indeed, a lot you need to know to develop for the Mac and iOS platforms. If you are just starting out and don’t have any programming experience, your first course of action should be to take a college-level course in the C programming language. Although the alphabet might start with the letter A, the root of most programming languages, and certainly your path as a developer, is C.

Once you know C and how to work with a compiler (something you’ll learn in that basic C course), the rest should be easy. From there, you’ll hop right on to Objective-C and learn how to program with that alongside the Cocoa frameworks. To help you along the way, my editor Chuck Toporek and I put together the flowchart shown in Figure P-1 to point you at some books of interest.

image

Figure P-1. What it takes to be an iOS programmer.

Once you know C, you’ve got a few options for learning how to program with Objective-C. For a quick-and-dirty overview of Objective-C, you can turn to Chapter 2 of this book and read the “Objective-C Boot Camp.” However, if you want a more in-depth view of the language, you can either read Apple’s own documentation or pick up one of these books on Objective-C:

Objective-C Programming: The Big Nerd Ranch Guide, by Aaron Hillegass (Big Nerd Ranch, 2012).

Learning Objective-C: A Hands-on Guide to Objective-C for Mac and iOS Developers, by Robert Clair (Addison-Wesley, 2011).

Programming in Objective-C 2.0, Fourth Edition, by Stephen Kochan (Addison-Wesley, 2012).

With the language behind you, next up is tackling Cocoa and the developer tools, otherwise known as Xcode. For that, you have a few different options. Again, you can refer to Apple’s own documentation on Cocoa and Xcode,1 or if you prefer books, you can learn from the best. Aaron Hillegass, founder of the Big Nerd Ranch in Atlanta,2 is the coauthor of iOS Programming: The Big Nerd Ranch Guide, Second Edition and author of Cocoa Programming for Mac OS X, Fourth Edition. Aaron’s book is highly regarded in Mac developer circles and is the most-recommended book you’ll see on the cocoa-dev mailing list. To learn more about Xcode, look no further than Fritz Anderson’s Xcode 4 Unleashed from Sams Publishing.


Note

There are plenty of other books from other publishers on the market, including the best-selling Beginning iPhone 4 Development, by Dave Mark, Jack Nutting, and Jeff LaMarche (Apress, 2011). Another book that’s worth picking up if you’re a total newbie to programming is Beginning Mac Programming, by Tim Isted (Pragmatic Programmers, 2011). Don’t just limit yourself to one book or publisher. Just as you can learn a lot by talking with different developers, you will learn lots of tricks and tips from other books on the market.


To truly master Mac development, you need to look at a variety of sources: books, blogs, mailing lists, Apple’s own documentation, and, best of all, conferences. If you get the chance to attend WWDC, you’ll know what I’m talking about. The time you spend at those conferences talking with other developers, and in the case of WWDC, talking with Apple’s engineers, is well worth the expense if you are a serious developer.

How This Book Is Organized

This book offers single-task recipes for the most common issues new iOS developers face: laying out interface elements, responding to users, accessing local data sources, and connecting to the Internet. Each chapter groups together related tasks, allowing you to jump directly to the solution you’re looking for without having to decide which class or framework best matches that problem.

The iOS 5 Developer’s Cookbook offers you “cut-and-paste convenience,” which means you can freely reuse the source code from recipes in this book for your own applications and then tweak the code to suit your app’s needs.

Here’s a rundown of what you find in this book’s chapters:

Chapter 1, “Introducing the iOS SDKChapter 1 introduces the iOS SDK and explores iOS as a delivery platform, limitations and all. It explains the breakdown of the standard iOS application and helps you get started with the iOS Developer Portal.

Chapter 2, “Objective-C Boot Camp—If you’re new to Objective-C as well as to iOS, you’ll appreciate this basic skills chapter. Objective-C is the standard programming language for both iOS and for Mac OS X. It offers a powerful object-oriented language that lets you build applications that leverage Apple’s Cocoa and Cocoa Touch frameworks. Chapter 2 introduces the language, provides an overview of its object-oriented features, discusses memory management skills, and adds a common class overview to get you started with Objective-C programming.

Chapter 3, “Building Your First ProjectChapter 3 covers the basics for building your first Hello World–style applications. It introduces Xcode and Interface Builder, showing how you can use these tools in your projects. You read about basic debugging tools, walk through using them, and pick up some tips about handy compiler directives. You’ll also discover how to create provisioning profiles and use them to deploy your application to your device, to beta testers, and to the App Store.

Chapter 4, “Designing InterfacesChapter 4 introduces iOS’s library of visual classes. It surveys these classes and their geometry. In this chapter, you learn how to work with these visual classes and discover how to handle tasks such as device reorientation. You’ll read about solutions for laying out and customizing interfaces and learn about hybrid solutions that rely both on Interface Builder–created interfaces and Objective-C-centered ones.

Chapter 5, “Working with View Controllers—The iOS paradigm in a nutshell is this: small screen, big virtual worlds. In Chapter 5, you discover the various view controller classes that enable you to enlarge and order the virtual spaces your users interact with. You learn how to let these powerful objects perform all the heavy lifting when navigating between iOS application screens or breaking down iPad applications into master-detail views.

Chapter 6, “Assembling Views and AnimationsChapter 6 introduces iOS views, objects that live on your screen. You see how to lay out, create, and order your views to create backbones for your applications. You read about view hierarchies, geometries, and animations, features that bring your iOS applications to life.

Chapter 7, “Working with ImagesChapter 7 introduces images, specifically the UIImage class, and teaches you all the basic know-how you need for working with iOS images. You learn how to load, store, and modify image data in your applications. You see how to add images to views and how to convert views into images. And you discover how to process image data to create special effects, how to access images on a byte-by-byte basis, and how to take photos with your device’s built-in camera.

Chapter 8, “Gestures and Touches—On iOS, the touch provides the most important way that users communicate their intent to an application. Touches are not limited to button presses and keyboard interaction. Chapter 8 introduces direct manipulation interfaces, multitouch, and more. You see how to create views that users can drag around the screen and read about distinguishing and interpreting gestures, as well as how to create custom gesture recognizers.

Chapter 9, “Building and Using Controls—Control classes provide the basis for many of iOS’s interactive elements, including buttons, sliders, and switches. This chapter introduces controls and their use. You read about standard control interactions and how to customize these objects for your application’s specific needs. You even learn how to build your own controls from the ground up, as Chapter 9 creates custom switches, star ratings controls, and a virtual touch wheel.

Chapter 10, “Working with Text—From text fields and text views to iOS’s new and powerful Core Text abilities and inline spelling checkers, Chapter 10 introduces everything you need to know to work with iOS text in your apps.

Chapter 11, “Creating and Managing Table Views—Tables provide a scrolling interaction class that works particularly well on a small, cramped device. Many, if not most, apps that ship with the iPhone and iPod touch center on tables, including Settings, YouTube, Stocks, and Weather. Chapter 11 shows how iPhone tables work, what kinds of tables are available to you as a developer, and how you can use table features in your own programs.

Chapter 12, “A Taste of Core Data—Core Data offers managed data stores that can be queried and updated from your application. It provides a Cocoa Touch–based object interface that brings relational data management out from SQL queries and into the Objective-C world of iPhone development. Chapter 12 introduces Core Data. It provides just enough recipes to give you a taste of the technology, offering a jumping-off point for further Core Data learning. You learn how to design managed database stores, add and delete data, and query that data from your code and integrate it into your UIKit table views.

Chapter 13, “Alerting the User—iOS offers many ways to provide users with a heads-up, from pop-up dialogs and progress bars to local notifications, popovers, and audio pings. Chapter 13 shows how to build these indications into your applications and expand your user-alert vocabulary. It introduces standard ways of working with these classes and offers solutions that allow you to craft linear programs without explicit callbacks.

Chapter 14, “Device Capabilities—Each iOS device represents a meld of unique, shared, momentary, and persistent properties. These properties include the device’s current physical orientation, its model name, battery state, and access to onboard hardware. Chapter 14 looks at the device from its build configuration to its active onboard sensors. It provides recipes that return a variety of information items about the unit in use. You read about testing for hardware prerequisites at runtime and specifying those prerequisites in the application’s Info.plist file. You discover how to solicit sensor feedback (including using Core Motion) and subscribe to notifications to create callbacks when those sensor states change. This chapter covers the hardware, file system, and sensors available on the iPhone device and helps you programmatically take advantage of those features.

Chapter 15, “Networking—As an Internet-connected device, iOS is particularly suited to subscribing to web-based services. Apple has lavished the platform with a solid grounding in all kinds of network computing services and their supporting technologies. Chapter 15 surveys common techniques for network computing and offers recipes that simplify day-to-day tasks. You read about network reachability, synchronous and asynchronous downloads, using operation queues, working with the iPhone’s secure keychain to meet authentication challenges, XML parsing, JSON serialization, the new Twitter APIs, and more.

About the Sample Code

For the sake of pedagogy, this book’s sample code usually presents itself in a single main.m file. This is not how people normally develop iPhone or Cocoa applications, or, honestly, how they should be developing them, but it provides a great way of presenting a single big idea. It’s hard to tell a story when readers must look through five or seven or nine individual files at once. Offering a single file concentrates that story, allowing access to that idea in a single chunk.

These examples are not intended as standalone applications. They are there to demonstrate a single recipe and a single idea. One main.m file with a central presentation reveals the implementation story in one place. Readers can study these concentrated ideas and transfer them into normal application structures, using the standard file structure and layout. The presentation in this book does not produce code in a standard day-to-day best-practices approach. Instead, it reflects a pedagogical approach that offers concise solutions that you can incorporate back into your work as needed.

Contrast that to Apple’s standard sample code, where you must comb through many files to build up a mental model of the concepts that are being demonstrated. Those examples are built as full applications, often doing tasks that are related to but not essential to what you need to solve. Finding just those relevant portions is a lot of work. The effort may outweigh any gains. In this book, there are two exceptions to this one-file rule:

• First, application-creation walkthroughs use the full file structure created by Xcode to mirror the reality of what you’d expect to build on your own. The walkthrough folders may therefore contain a dozen or more files at once.

• Second, standard class and header files are provided when the class itself is the recipe or provides a precooked utility class. Instead of highlighting a technique, some recipes offer these precooked class implementations and categories (that is, extensions to a preexisting class rather than a new class). For those recipes, look for separate .m and .h files in addition to the skeletal main.m that encapsulates the rest of the story.

For the most part, the examples for this book use a single application identifier: com.sadun.helloworld. This book uses one identifier to avoid clogging up your iOS devices with dozens of examples at once. Each example replaces the previous one, ensuring that your home screen remains relatively uncluttered. If you want to install several examples at once, simply edit the identifier, adding a unique suffix, such as com.sadun.helloworld.table-edits. You can also edit the custom display name to make the apps visually distinct. Your Team Provisioning Profile matches every application identifier, including com.sadun.helloworld. This allows you to install compiled code to devices without having to change the identifier; just make sure to update your signing identity in each project’s build settings.

Getting the Sample Code

The source code for this book can be found at the open-source GitHub hosting site at https://github.com/erica/iOS-5-Cookbook. There, you find a chapter-by-chapter collection of source code that provides working examples of the material covered in this book.

Sample code is never a fixed target. It continues to evolve as Apple updates its SDK and the Cocoa Touch libraries. Get involved. You can pitch in by suggesting bug fixes and corrections as well as by expanding the code that’s on offer. GitHub allows you to fork repositories and grow them with your own tweaks and features, and share those back to the main repository. If you come up with a new idea or approach, let me know. My team and I are happy to include great suggestions both at the repository and in the next edition of this Cookbook.

Getting Git

You can download this Cookbook’s source code using the git version control system. A Mac OS X implementation of git is available at http://code.google.com/p/git-osx-installer. Mac OS X git implementations include both command-line and GUI solutions, so hunt around for the version that best suits your development needs.

Getting GitHub

GitHub (http://github.com) is the largest git-hosting site, with more than 150,000 public repositories. It provides both free hosting for public projects and paid options for private projects. With a custom web interface that includes wiki hosting, issue tracking, and an emphasis on social networking of project developers, it’s a great place to find new code or collaborate on existing libraries. You can sign up for a free account at their website, allowing you to copy and modify the Cookbook repository or create your own open-source iOS projects to share with others.

Contacting the Author

If you have any comments or questions about this book, please drop me an e-mail message at [email protected], or stop by www.ericasadun.com for updates about the book and news for iOS developers. Please feel free to visit, download software, read documentation, and leave your comments.

Endnotes

1 See the Cocoa Fundamentals Guide (http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaFundamentals.pdf) for a head start on Cocoa, and for Xcode, see A Tour of Xcode (http://developer.apple.com/mac/library/documentation/DeveloperTools/Conceptual/A_Tour_of_Xcode/A_Tour_of_Xcode.pdf).

2 Big Nerd Ranch: http://www.bignerdranch.com.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.13.5