Preface - The Core iOS Developer’s Cookbook, Fifth Edition (2014)

The Core iOS Developer’s Cookbook, Fifth Edition (2014)

Preface

Welcome to a new Core iOS Developer’s Cookbook!

With iOS 7, Apple introduced the most significant changes to its mobile operating system since its inception. This cookbook is here to help you get started developing for the latest exciting release. This revision introduces all the new features and visual paradigms announced at the latest Worldwide Developers Conference (WWDC), showing you how to incorporate them into your applications.

For this edition, the publishing team has split the cookbook material into manageable print volumes. This book, The Core iOS Developer’s Cookbook, provides solutions for the heart of day-to-day development. It covers all the classes you need for creating iOS applications using standard APIs and interface elements. It provides recipes you need for working with graphics, touches, and views to create mobile applications.

And there’s Learning iOS Development: A Hands-on Guide to the Fundamentals of iOS Programming, which covers much of the tutorial material that used to comprise the first several chapters of the cookbook. There you’ll find all the fundamental how-to you need to learn iOS 7 development from the ground up. From Objective-C to Xcode, debugging to deployment, Learning iOS Development teaches you how to get started with Apple’s development tool suite.

As in the past, you can find sample code at GitHub. You’ll find the repository for this Cookbook at https://github.com/erica/iOS-7-Cookbook, all of it refreshed for iOS 7 after WWDC 2013.

If you have suggestions, bug fixes, corrections, or anything else you’d like to contribute to a future edition, please contact us at erica@ericasadun.com or rich@lifeisrich.org. We thank you all in advance. We appreciate all your feedback, which helps make this a better, stronger book.

—Erica Sadun and Rich Wardwell, January 2014

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 iOS device to test your applications, preferably a new model iPhone or iPad. The following list covers the basics of what you’ll need to begin:

Image Apple’s iOS SDK—You can download the latest version of the iOS SDK from Apple’s iOS Dev Center (http://developer.apple.com/ios). If you plan to sell apps through the App Store, you need to become a paid iOS developer. This 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 or iPad for testing and debugging and to gain early access to prerelease versions of iOS. Free-program developers can test their software on the Mac-based simulator but cannot deploy to devices or submit to the App Store.

Image A modern Mac running Mac OS X Mountain Lion (v 10.8) or, preferably, Mac OS X Mavericks (v 10.9)—You need plenty of disk space for development, and your Mac should have as much RAM as you can afford to put into it.

Image An iOS device—Although the iOS SDK includes a simulator for you to test your applications, you really do need to own iOS hardware to develop for the platform. You can 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 that you can test on the same platforms your target audience will use.

Image An Internet connection—This connection enables you to test your programs with a live Wi-Fi connection as well as with a cellular data service.

Image 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, you should be able to make the move to Objective-C.

Your Roadmap to Mac/iOS Development

One book can’t be everything to everyone. If we were to pack everything you 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 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. The flowchart in Figure P-1 shows the key titles offered by Pearson Education that can help provide the training you need to become a skilled iOS developer.

Image

Figure P-1 A roadmap to becoming an iOS developer.

Once you know C, you’ve got a few options for learning how to program with Objective-C. If you want an in-depth view of the language, you can either read Apple’s own documentation or pick up one of these books on Objective-C:

Image Objective-C Programming: The Big Nerd Ranch Guide, 2nd edition, by Aaron Hillegass and Mikey Ward (Big Nerd Ranch, 2013)

Image Learning Objective-C 2.0: A Hands-on Guide to Objective-C for Mac and iOS Developers, 2nd edition, by Robert Clair (Addison-Wesley, 2012)

Image Programming in Objective-C 2.0, 6th edition, by Stephen Kochan (Addison-Wesley, 2012)

With the language under your belt, next up is tackling Cocoa (Mac) or Cocoa Touch (iOS) 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, Cocoa Touch, and Xcode (Apple Developer: developer.apple.com), or if you prefer books, you can learn from the best. Aaron Hillegass, founder of the Big Nerd Ranch in Atlanta (www.bignerdranch.com), is the coauthor of iOS Programming: The Big Nerd Ranch Guide, 2nd edition, and author of Cocoa Programming for Mac OS X, 4th 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.


Note

There are plenty of other books from other publishers on the market, including the bestselling Beginning iOS 6 Development by Dave Mark, Jack Nutting, Jeff LaMarche, and Fredrik Olsson (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 or iOS 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 a chance to attend WWDC, you’ll know what we’re talking about. The time you spend at 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 Core iOS 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 the needs of each of your apps.

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

Image Chapter 1, “Gestures and Touches—On iOS, touch provides the most important way for users to communicate their intent to an application. Touches are not limited to button presses and keyboard interaction. This chapter introduces direct manipulation interfaces, Multi-Touch, and more. You’ll 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.

Image Chapter 2, “Building and Using Controls—Take your controls to the next level. This chapter introduces everything you need to know about how controls work. You’ll discover how to build and customize controls in a variety of ways. From the prosaic to the obscure, this chapter introduces a range of control recipes you can reuse in your programs.

Image Chapter 3, “Alerting the User—iOS offers many ways to provide users with heads-ups, from pop-up dialogs and progress bars to local notifications, popovers, and audio pings. This chapter 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 use a blocks-based API to easily handle alert interactions.

Image Chapter 4, “Assembling Views and Animations—The UIView class and its subclasses populate the iOS device screens. This chapter introduces views from the ground up. This chapter dives into view recipes, exploring ways to retrieve, animate, and manipulate view objects. You’ll learn how to build, inspect, and break down view hierarchies and understand how views work together. You’ll discover the role that geometry plays in creating and placing views into your interface, and you read about animating views so they move and transform onscreen.

Image Chapter 5, “View Constraints—Auto Layout revolutionized view layout in iOS. Apple’s layout features make your life easier and your interfaces more consistent. This is especially important when working across members of the same device family with different screen sizes, dynamic interfaces, rotation, or localization. This chapter introduces code-level constraint development. You’ll discover how to create relations between onscreen objects and specify the way iOS automatically arranges your views. The outcome is a set of robust rules that adapt to screen geometry.

Image Chapter 6, “Text Entry—This chapter introduces text recipes that support a wide range of solutions. You’ll read about controlling keyboards, making onscreen elements “text aware,” scanning text, formatting text, and so forth. From text fields and text views to iOS’s inline spelling checkers, this chapter introduces everything you need to know to work with iOS text in your apps.

Image Chapter 7, “Working with View Controllers—In this chapter, you’ll discover the various view controller classes that enable you to enlarge and order the virtual spaces your users interact with. You’ll learn from how-to recipes that cover page view controllers, split view controllers, navigation controllers, and more.

Image Chapter 8, “Common Controllers—The iOS SDK provides a wealth of system-supplied controllers that you can use in your day-to-day development tasks. This chapter introduces some of the most popular ones. You’ll read about selecting images from your photo library, snapping photos, and recording and editing videos. You’ll discover how to allow users to compose e-mails and text messages and how to post updates to social media such as Twitter and Facebook.

Image Chapter 9, “Creating and Managing Table Views—Tables provide a scrolling interaction class that works particularly well both on smaller devices and as a key player on larger tablets. Many iOS apps center on tables due to their simple natural organization features. This chapter introduces tables, explaining how tables work, what kinds of tables are available to you as a developer, and how you can leverage table features in your applications.

Image Chapter 10, “Collection Views—Collection views use many of the same concepts as tables but provide more power and more flexibility. This chapter walks you through all the basics you need to get started. Prepare to read about creating side-scrolling lists, grids, one-of-a-kind layouts like circles, and more. You’ll learn about integrating visual effects through layout specifications and snapping items into place after scrolling, and you’ll discover how to take advantage of built-in animation support to create the most effective interactions possible.

Image Chapter 11, “Documents and Data Sharing—Under iOS, applications can share information and data as well as move control from one application to another, using several system-supplied features. This chapter introduces the ways you can integrate documents and data sharing between applications. You’ll see how to add these features into your applications and use them smartly to make your apps cooperative citizens of the iOS ecosystem.

Image 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 iOS development. This chapter 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’ll learn how to design managed database stores, add and delete data, and query data from your code and integrate it into your UIKit table views and collection views.

Image Chapter 13, “Networking Basics—On Internet-connected devices, 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. This chapter surveys common techniques for network computing and offers recipes that simplify day-to-day tasks. This chapter introduces the new HTTP system in iOS 7 and provides examples for downloading data, including background downloading. You’ll also read about network reachability and web services, including examples of XML parsing and JSON serialization utilizing live services.

Image Chapter 14, “Device-Specific Development—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, its battery state, and its access to onboard hardware. This chapter 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.

Image Chapter 15, “Accessibility—This chapter offers a brief overview of VoiceOver accessibility to extend your audience to the widest possible range of users. You’ll read about adding accessibility labels and hints to your applications and testing those features in the simulator and on the iOS device.

Image Appendix A, “Objective-C Literals—This appendix introduces new Objective-C constructs for specifying numbers, arrays, and dictionaries.

About the Sample Code

For the sake of pedagogy, this book’s sample code uses 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 that requires looking 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.

The examples in this book are not intended as standalone applications. Each is here 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 pedagogy that offers concise solutions that you can incorporate into your work as needed.

Contrast this 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 involving tasks that are related to but not essential to what you need to solve. Finding just the relevant portions is a lot of work, and the effort may outweigh any gains.

In this book, you’ll find exceptions to this one-file-with-the-story rule: This book provides standard class and header files when a class implementation is the recipe. Instead of highlighting a technique, some recipes offer these classes 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 in 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 simultaneously, simply edit the identifier by 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

You’ll find the source code for this book at github.com/erica/iOS-7-Cookbook on the open-source GitHub hosting site. There you’ll find a chapter-by-chapter collection of source code that provides working examples of the material covered in this book. Recipes are numbered as they are in the book. Recipe 6 in Chapter 5, for example, appears in the 06 subfolder of the C05 folder.

Any project numbered 00 or that has a suffix (like 05b or 02c) refers to material that is used to create in-text coverage and figures. For example, Chapter 9’s 00 – Cell Types project helped build Figure 9-2, showing system-supplied table view cell styles. Normally, we delete these extra projects. Early readers of this manuscript requested that we include them in this edition. You’ll find a half dozen or so of these extra samples scattered around the repository.

Contribute!

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 to share them back to the main repository. If you come up with a new idea or approach, let us know. Our team is happy to include great suggestions both at the repository and in the next edition of this book.

Getting Git

You can download this book’s source code by using the git version control system. Xcode 5 includes robust support for git within the IDE. The git command-line tool is also packaged with the Xcode 5 toolset. Numerous third-party free and commercial git tools are also available.

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 for project developers, it’s a great place to find new code and collaborate on existing libraries. You can sign up for a free account at the GitHub website, where you can also copy and modify the repository for this book or create your own open-source iOS projects to share with others.