cover.eps

iOS 6 Programming Pushing the Limits

Table of Contents

Introduction
Who This Book Is For
What This Book Covers
What Is New in This Edition
How This Book Is Structured
Part I: What’s New?
Part II: Getting the Most Out of Everyday Tools
Part III: The Right Tool for the Job
Part IV: Pushing the Limits
What You Need to Use This Book
Finding Apple Documentation
Source Code
Errata
Part I: What’s New?
Chapter 1: The Brand New Stuff
What’s New
Collection Views
Auto Layout
Automatic Reference Counting
In App Purchases Hosted Content
Social Framework
UI State Preservation
Other New Features
Summary
Further Reading
Apple Documentation
Chapter 2: Getting Comfortable with Xcode 4 and the LLVM Compiler
Getting to Know the User Interface
Tabbed Editor
Changes to Key Bindings
Project Settings Editor
Integrated Version Control
Workspaces
All in One Window
Navigating the Navigators
Project Navigator
Symbol Navigator
Search Navigator
Issue Navigator
Debug Navigator
Breakpoint Navigator
Log Navigator
Help from Your Assistant
Integrated Interface Builder
Interface Builder Panels
LLVM Compiler: A Tryst with the Brain
The Clang Front End
I’m a Bug! Fix Me
What’s New in LLVM 4
Literals
Literals and Availability
Auto Synthesis of Instance Variables
Git Your Versions Here
Integrated Git Version Control System
Versions Editor
Git Best Practices
Schemes
Why Schemes?
Think of Schemes as Implementing Your Intentions
Creating a Scheme
Sharing Your Schemes
Build Configurations You Can Comment
Creating an xcconfig File
Refactoring the Build Configuration File
Migrating Your Code to Objective-C ARC
Using the Convert to Objective-C ARC Tool
Xcode 4 Organizer
Automatic Device Provisioning
Viewing Crash Logs and Console NSLog Statements
Viewing an Application’s Sandbox Data
Managing Repositories
Accessing Your Application Archives
Viewing Objective-C and SDK Documentation
Summary
Further Reading
Apple Documentation
WWDC Sessions
Blogs
Web Resources
Books
Part II: Getting the Most Out of Everyday Tools
Chapter 3: Everyday Objective-C
Naming Conventions
Automatic Reference Counting
Properties
Property Attributes
Property Best Practices
Private Ivars
Accessors
Categories and Extensions
+load
Category Data Using Associative References
Class Extensions
Formal and Informal Protocols
Summary
Further Reading
Apple Documentation
Other Resources
Chapter 4: Hold On Loosely: Cocoa Design Patterns
Understanding Model-View-Controller
Using Model Classes
Using View Classes
Using Controller Classes
Understanding Delegates and Data Sources
Working with the Command Pattern
Using Target-Action
Using Method Signatures and Invocations
Using Trampolines
Using Undo
Working with the Observer Pattern
Working with the Singleton Pattern
Summary
Further Reading
Apple Documentation
Other Resources
Chapter 5: Memory Management with Objective-C ARC
Introduction to Objective-C ARC
A Brief History
Manual Versus Automatic Reference Counting
What Is ARC?
Integrating Non-ARC Third-Party Code into Your ARC Project
Integrating ARC Code into Your Non-ARC Project
ARC Code in a Framework
ARC nils Declared Variables
Objective-C Naming Conventions
Overriding the Default Behavior
Toll-Free Bridging
ARC Internals
Common ARC Migration Errors
Workarounds When Using ARC
Summary
Further Reading
Apple Documentation
WWDC Sessions
Blogs
Chapter 6: Getting Table Views Right
UITableView Class Hierarchy
Understanding Table Views
UITableViewController
UITableViewCell
Speed Up Your Table View Scrolling
Custom Nonrepeating Cells
Table View Best Practices: Writing Clean Code with Lean Controllers
Summary
Further Reading
Apple Documentation
Other Resources
Chapter 7: Great at Any Angle: Collection Views and Auto Layout
Collection Views
Classes and Protocols
Example
Cocoa Auto Layout
Using Auto Layout
Getting Started with Auto Layout
Relative Layout Constraints
Visual Format Language
Debugging Layout Errors
Summary
Further Reading
Apple Documentation
WWDC Sessions
Chapter 8: Better Drawing
iOS’s Many Drawing Systems
UIKit and the View Drawing Cycle
View Drawing Versus View Layout
Custom View Drawing
Drawing with UIKit
Paths
Understanding Coordinates
Resizing and contentMode
Transforms
Drawing with Core Graphics
Mixing UIKit and Core Graphics
Managing Graphics Contexts
Optimizing UIView Drawing
Avoid Drawing
Caching and Background Drawing
Custom Drawing Versus Prerendering
Pixel Alignment and Blurry Text
Alpha, Opaque, Hidden
CGLayer
Summary
Further Reading
Apple Documentation
Other Resources
Chapter 9: Layers Like an Onion: Core Animation
View Animations
Managing User Interaction
Drawing with Layers
Setting Contents Directly
Implementing Display
Custom Drawing
Drawing in Your Own Context
Moving Things Around
Implicit Animations
Explicit Animations
Model and Presentation
A Few Words on Timings
Into the Third Dimension
Decorating Your Layers
Auto-Animate with Actions
Animating Custom Properties
Core Animation and Threads
Summary
Further Reading
Apple Documentation
Other Resources
Chapter 10: Tackling Those Pesky Errors
Error-Handling Patterns
Assertions
Exceptions
Catching and Reporting Crashes
Errors and NSError
Error Localization
Error Handler Blocks
Logs
Logging Sensitive Information
Getting Your Logs
Summary
Further Reading
Apple Documentation
Other Resources
Chapter 11: Location Services: Know Where You Are
Core Location Framework
Tapping into the User’s Location
Getting the User’s Heading with the Built-In Compass
Location Services and Privacy
Background Location
Getting Continuous Location Updates in the Background
Subscribing to Significant Change Notification
Region Monitoring (Geo-Fencing)
Location Simulation
Keeping an Eye on the Battery
Summary
Further Reading
Apple Documentation
Part III: The Right Tool for the Job
Chapter 12: Common UI Paradigms Using Table Views
Pull-To-Refresh
iOS Pull-to-Refresh
Infinite Scrolling
Inline Editing and Keyboard
Animating a UITableView
Practical Implementations of Table View Animations
Implementing an Accordion List
Implementing a Drawer
Using Gesture Recognizers in Table View Cells
Summary
Further Reading
Apple Documentation
Chapter 13: Controlling Multitasking
Best Practices for Backgrounding: With Great Power Comes Great Responsibility
When We Left Our Heroes: State Restoration
Testing State Restoration
Opting In
Startup Changes
Restoration Identifiers
State Encoders and Decoders
Table Views and Collection Views
Advanced Restoration
Introduction to Multitasking and Run Loops
Developing Operation-Centric Multitasking
Setting Maximum Concurrent Operations
Multitasking with Grand Central Dispatch
GCD and ARC
Sources and Timers
Creating Synchronization Points with Dispatch Barriers
Queue Targets and Priority
Dispatch Groups
Queue-Specific Data
Dispatch Data
Summary
Further Reading
Apple Documentation
WWDC Sessions
Other Resources
Chapter 14: REST for the Weary
The REST Philosophy
Choosing Your Data Exchange Format
Parsing XML on iOS
Parsing JSON on iOS
XML Versus JSON
Model Versioning
A Hypothetical Web Service
Important Reminders
RESTfulEngine Architecture (iHotelApp Sample Code)
NSURLConnection Versus Third-Party Frameworks
Creating the RESTfulEngine
Authenticating Your API Calls with Access Tokens
Overriding Methods to Add Custom Authentication Headers in RESTfulEngine.m
Canceling Requests
Request Responses
Key Value Coding JSONs
List Versus Detail JSON Objects
Nested JSON Objects
Less Is More
Error Handling
Localization
Handling Additional Formats Using Category Classes
Tips to Improve Performance on iOS
Summary
Further Reading
Apple Documentation
Other Resources
Chapter 15: Batten the Hatches with Security Services
Understanding the iOS Sandbox
Securing Network Communications
How Certificates Work
Checking Certificate Validity
Determining Certificate Trust
Employing File Protection
Using Keychains
Sharing Data with Access Groups
Using Encryption
Overview of AES
Converting Passwords to Keys with PBKDF2
AES Mode and Padding
The Initialization Vector (IV)
Authentication with HMAC
Bad Passwords
Performing One-Shot Encryption
Improving CommonCrypto Performance
Combining Encryption and Compression
Summary
Further Reading
Apple Documentation
WWDC Sessions
Other Resources
Chapter 16: Running on Multiple iPlatforms and iDevices
Developing for Multiple Platforms
Configurable Target Settings: Base SDK Versus Deployment Target
Considerations for Multiple SDK Support: Frameworks, Classes, and Methods
Checking the Availability of Frameworks, Classes, and Methods
Detecting Device Capabilities
Detecting Devices and Assuming Capabilities
Detecting Hardware and Sensors
In App Email and SMS
Checking Multitasking Awareness
Obtaining the UIDevice+Additions Category
Supporting the iPhone 5
UIRequiredDeviceCapabilities
Summary
Further Reading
Apple Documentation
Other Resources
Chapter 17: Internationalization and Localization
What Is Localization?
Localizing Strings
Auditing for Nonlocalized Strings
Formatting Numbers and Dates
Nib Files and Base Internationalization
Localizing Complex Strings
Summary
Further Reading
Apple Documentation
WWDC Sessions
Chapter 18: Selling Past the Sale with In App Purchases
Before You Start
In App Purchase Products
Prohibited Items
Rethinking Your Business Model
Setting Up Products on iTunes Connect
Step 1: Create a New App ID for Your App
Step 2: Generate Provisioning Profiles
Step 3: Create the App’s Product Entry
Step 4: Create the In App Purchase Product Entries
Step 5: Generating the Shared Secret
Step 6: Creating Test User Accounts
Step 7: Creating Hosted Content
In App Purchase Implementation
Introduction to MKStoreKit
Why MKStoreKit?
Design of MKStoreKit
Customizing MKStoreKit
Making the Purchase
Downloading Hosted Content
Testing Your Code
Troubleshooting
Invalid Product IDs
Cannot Connect to iTunes Store
You Have Already Purchased This Product, but It’s Still Not Downloaded
Summary
Further Reading
Apple Documentation
Blogs
Other Resources
Chapter 19: Debugging
LLDB
Debugging with LLDB
Debug Information File (dSYM file)
Symbolication
Breakpoints
The Breakpoint Navigator
Watchpoints
The LLDB Console
NSZombieEnabled Flag
Different Types of Crashes
EXC_BAD_ACCESS
SIGSEGV
SIGBUS
SIGTRAP
EXC_ARITHMETIC
SIGILL
SIGABRT
Watchdog Timeout
Custom Error Handling for Signals
Collecting Crash Reports
iTunes Connect
Third-Party Crash Reporting Services
Advantages of TestFlight or HockeyApp over iTunes Connect
Summary
Further Reading
Apple Documentation
WWDC Session
Other Resources
Chapter 20: Performance Tuning Until It Flies
The Performance Mindset
Rule 1: The App Exists to Delight the User
Rule 2: The Device Exists for the Benefit of the User
Rule 3: Go to Extremes
Rule 4: Perception Is Reality
Rule 5: Focus on the Big Wins
Welcome to Instruments
Finding Memory Problems
A Word on Memory Allocation
Finding CPU Problems
The Accelerate Framework
GLKit
Drawing Performance
Core Image
Optimizing Disk and Network Access
Summary
Further Reading
Apple Documentation
Other Resources
Part IV: Pushing the Limits
Chapter 21: Storyboards and Custom Transitions
Getting Started with Storyboards
Instantiating a Storyboard
Loading View Controllers Within a Storyboard
Segues
Building Table Views with Storyboard
Custom Transitions
Another Advantage
Disadvantages
Customizing Your Views Using UIAppearance Protocol
Summary
Further Reading
Apple Documentation
WWDC Sessions
Other Resources
Chapter 22: Cocoa’s Biggest Trick: Key-Value Coding and Observing
Key-Value Coding
Setting Values with KVC
Traversing Properties with Key Paths
KVC and Collections
KVC and Dictionaries
KVC and Nonobjects
Higher-Order Messaging with KVC
Collection Operators
Key-Value Observing
KVO and Collections
How Is KVO Implemented?
KVO Tradeoffs
Summary
Further Reading
Apple Documentation
Other Resources
Chapter 23: Think Different: Blocks and Functional Programming
What Is a Block?
Why Use Functional Programming?
A “Functional” UIAlertView
Declaring a Block
Scope of Variables
Stack Versus Heap
Implementing a Block
Block-Based UIAlertView
Blocks and Concurrency
Dispatch Queues in GCD
NSOperationQueue Versus GCD Dispatch Queue
Block-Based Cocoa Methods
UIView Animations Using Blocks
Presenting and Dismissing View Controllers
TweetComposer Versus In App E-mail/SMS
Dictionary Enumeration Using NSDictionary enumerateWithBlock
Looking for Block-Based Methods
Supported Platforms
Summary
Further Reading
Apple Documentation
Blogs
Other Resources
Chapter 24: Going Offline
Reasons for Going Offline
Strategies for Caching
Storing the Cache
Cache Versioning and Invalidation
Data Model Cache
Cache Versioning
Invalidating the Cache
Creating an In-Memory Cache
Designing the In-Memory Cache for AppCache
Handling Memory Warnings
Handling Termination and Entering Background Notifications
Creating a URL Cache
Expiration Model
Validation Model
Example
Caching Images with a URL Cache
Summary
Further Reading
Apple Documentation
Books
Other Resources
Chapter 25: Data in the Cloud
iCloud
Understanding the iCloud Data Store
Third-Party Cloud Offerings
Parse
Getting Started with Parse
Parse Top Level Objects
Code
StackMob
Setting Up StackMob
Logging In and Uploading and Retrieving Data
StackMob Custom Code
Disadvantages of Using a Backend as a Service
Summary
Further Reading
Apple Documentation
WWDC Sessions
Other Resources
Chapter 26: Fancy Text Layout
The Normal Stuff: Fields, Views, and Labels
Rich Text in UIKit
Understanding Bold, Italic, and Underline
Attributed Strings
Paragraph Styles
Attributed Strings and HTML
Web Views for Rich Text
Displaying and Accessing HTML in a Web View
Responding to User Interaction
Drawing Web Views in Scroll and Table Views
Core Text
Simple Layout with CTFramesetter
Creating Frames for Noncontiguous Paths
Typesetters, Lines, Runs, and Glyphs
Drawing Text Along a Curve
Summary
Further Reading
Apple Documentation
WWDC Sessions
Other Resources
Chapter 27: Building a (Core) Foundation
Core Foundation Types
Naming and Memory Management
Allocators
Introspection
Strings and Data
Constant Strings
Creating Strings
Converting to C Strings
Other String Operations
Backing Storage for Strings
CFData
Collections
CFArray
CFDictionary
CFSet, CFBag
Other Collections
Callbacks
Toll-Free Bridging
Summary
Further Reading
Apple Documentation
Other Resources
Chapter 28: Deep Objective-C
Understanding Classes and Objects
Working with Methods and Properties
How Message Passing Really Works
Dynamic Implementations
Fast Forwarding
Normal Forwarding
Forwarding Failure
The Flavors of objc_msgSend
Method Swizzling
ISA Swizzling
Method Swizzling Versus ISA Swizzling
Summary
Further Reading
Apple Documentation
Other Resources

iOS 6 Programming Pushing the Limits

Publisher’s Acknowledgements

Some of the people who helped bring this book to market include the following:

Editorial and Production

VP Consumer and Technology Publishing Director: Michelle Leete

Associate Director–Book Content Management: Martin Tribe

Associate Publisher: Chris Webb

Acquisitions Editor: Craig Smith

Assistant Editor: Ellie Scott

Development Editor: Tom Dinse

Copy Editor: Melba Hopper

Technical Editor: Jay Thrash

Editorial Manager: Jodi Jensen

Senior Project Editor: Sara Shlaer

Editorial Assistant: Leslie Saxman

Marketing

Associate Marketing Director: Louise Breinholt

Marketing Manager: Lorna Mein

Senior Marketing Executive: Kate Parrett

Composition Services

Compositor: Indianapolis Composition Services

Proofreader: Cynthia Fields

Indexer: Potomac Indexing, LLC

About the Authors

Rob Napier is a builder of tree houses, hiker, and proud father. He began developing for the Mac in 2005, and picked up iPhone development when the first SDK was released, working on products such as The Daily, PandoraBoy, and Cisco Mobile. He is a major contributor to Stack Overflow and maintains the Cocoaphony blog (cocoaphony.com).

Mugunth Kumar is an independent iOS developer based in Singapore. He graduated in 2009 and holds a Masters degree from Nanyang Technological University, Singapore, majoring in Information Systems. He writes about mobile development, software usability, and iOS-related tutorials on his blog (blog.mugunthkumar.com). Prior to iOS development he worked for Fortune 500 companies GE and Honeywell as a software consultant on Windows and .NET platforms. His core areas of interest include programming methodologies (Object Oriented and Functional), mobile development and usability engineering. If he were not coding, he would probably be found at some exotic place capturing scenic photos of Mother Nature.

Dedication

To Neverwood. Thanks for your patience.
Rob

To my mother who shaped the first twenty years of my life
Mugunth

About the Technical Editor

Jay Thrash is a veteran software developer who has spent the past three years designing and developing iOS applications. During his career, he developed a keen interest in the areas of user interaction and interface design.

Prior to settling down as an iOS developer, Jay has worked on a variety of platforms and applications, including flight simulators and web application development. He has also spent over six years in the PC and console gaming industry.

Authors’ Acknowledgments

After spending much of last year writing for iOS 5, Rob thanks his family for their patience as he did it all again for iOS 6. Mugunth thanks his parents and friends for their support while writing this book. Thanks to Wiley, especially Craig Smith and Ellie Scott, for the continued support, encouragement, and nudging that it takes to get a book out the door. Thanks to Jay Thrash for jumping into the fray and tech editing for us, and to Tom Dinse who made sure that it was intelligible. Thanks to the Apple engineers at WWDC who put up with a deluge of questions, probing, and occasional complaining. And special thanks to Steve Jobs for a lifetime of elegant boxes. He will be missed.

Introduction

Apple has a history of alternating its releases between being user-focused and developer-focused. iOS 6 is mostly about users. There’s a totally new map interface with turn-by-turn driving directions. Social networks permeate the interface. Pass Kit opens up whole new ways to integrate the iPhone with daily life. The Siri enhancements make the iPhone 4S even more compelling. Expect users to upgrade quickly.

That’s great news, because iOS 6 is an exciting release for developers, too. So many things have gotten so much easier. It’s easier to lay out your UI with collection views and auto layout. UIKit has added rich text support. When your apps go into the background, state preservation makes it easy to keep track of where you were. Many things that were hard or tedious just became a lot simpler.

If you’re ready to take on the newest Apple release and push your application to the limits, this book will get you there.

Who This Book Is For

This is not an introductory book. Many other books out there cover Objective-C and will walk you step by step through Interface Builder. However, this book assumes that you have a little experience with iOS. Maybe you’re self-taught, or maybe you’ve taken a class. You’ve hopefully written at least most of an application, even if you haven’t submitted it yet. If you’re ready to move beyond the basics, to learn the best practices and the secrets that the authors have gleaned from practical experience writing real applications, then this is the book for you.

This book also is not just a list of recipes. There’s plenty of sample code here, but the focus is on discovering how to design, code, and maintain great iOS apps. Much of this book is about why rather than just how. You’ll find out as much about design patterns and writing reusable code as about syntax and new frameworks.

What This Book Covers

The iOS platforms always move forward, and so does this book. Most of the examples here require at least iOS 5, and many require iOS 6. All examples use Automatic Reference Counting, automatic property synthesis, and object literals. Except in a very few places, this book will not cover backward compatibility. If you’ve been shipping code long enough to need backward compatibility, you probably know how to deal with it. This book is about writing the best possible apps using the best features available.

This book focuses on iPhone 4, iPad 2, and higher models. Most topics here are applicable to the original iPad, iPod touch, iPhone 3GS, and Apple TV. Chapter 16 is devoted to dealing with the differences between the platforms.

What Is New in This Edition

This edition covers most of the newest additions to iOS 6, including collection views and Auto Layout (Chapter 7), and a complete chapter is dedicated to Automatic Reference Counting. We have added a whole new chapter explaining how to move your data to the cloud, covering some third-party backend as a service (BaaS) offerings. More relevant to iOS, this year saw the greatest improvement in the LLVM compiler and debugger. We expanded the LLVM section in Chapter 2 to highlight the important features of LLVM that you could use to write the next-generation apps. We also added a whole new chapter dedicated to debugging with LLDB (Chapter 19), covering advanced topics, including Python scripting, knowing the layout of registers, and reading the registers to solve the most difficult debugging problems. That chapter also provides a brief look at some command-line tools such as otool and atos that can help you with debugging. Lastly, Chapter 20 is dedicated to showing how to optimize your CPU performance, memory usage, network bandwidth, and battery-using Instruments.

Even if you have the previous edition of this book, the new coverage on debugging (Chapter 19), performance tuning (Chapter 20), and collection views and Auto Layout (Chapter 7) will probably be enough to convince you that you need a copy of this edition.

How This Book Is Structured

iOS has a very rich set of tools, from high-level frameworks like UIKit to very low-level tools like Core Text. Often, there are several ways to achieve a goal. As a developer, how do you pick the right tool for the job?

This book separates the everyday from the special purpose, helping you pick the right solution to each problem. You’ll discover why each framework exists, how the frameworks relate to each other, and when to choose one over another. Then you’ll learn how to make the most of each framework for solving its type of problem.

There are four parts to this book, moving from the most common tools to the most powerful. Chapters that are new in this edition or have been extensively updated are indicated.

Part I: What’s New?

If you’re familiar with iOS 5, then this section quickly introduces you to the new features of iOS 6.

(Updated) Chapter 1: “The Brand New Stuff”—iOS 6 adds a lot of new features, and here you get a quick overview of what’s available.

(Updated) Chapter 2: “Getting Comfortable with Xcode 4 and the LLVM compiler”—Xcode 4 is a huge IDE, and many of its features aren’t obvious. Whether you’re new to Xcode or a veteran from earlier versions, this chapter will help you make the most of this powerful (and sometimes frustrating) tool.

Part II: Getting the Most Out of Everyday Tools

As an iOS developer, you’ve encountered a wide variety of common tools, from notifications to table views to animation layers. But are you using these tools to their full potential? In this part, you find the best practices from seasoned developers in Cocoa development.

Chapter 3: “Everyday Objective-C”—If you’re ready to move to the next level in Objective-C, this chapter introduces you to the tools experienced developers use every day to improve application design, maintainability, and reusability.

Chapter 4: “Hold On Loosely: Cocoa Design Patterns”—Cocoa relies on a number of common and consistent design patterns. You discover what they are so you can solve problems the same way Apple does.

(New) Chapter 5: “Memory Management with Objective-C ARC”—Automatic Reference Counting has radically changed how iOS developers work. While most of the conversion is easy, migrating your code and your practices can create some subtle problems. You find out how to avoid the problems and get the most out of this powerful technology.

Chapter 6: “Getting Table Views Right”—Table views are perhaps the most complex and commonly used UI element in iOS. They are simple and elegant in design, but confusing to developers who don’t understand how they work. You learn how to use them correctly and how to solve some special problems like infinite scrolling.

(New) Chapter 7: “Great at Any Angle: Collection Views and Auto Layout”—Nothing created as much buzz at WWDC 2012 as UICollectionView. Up until now, UITableView has dominated iOS interfaces, but that will likely change in iOS 6 as developers master this new control. With the addition of constraint-based layout from OS X, incredibly complex and beautiful interfaces are now much simpler to implement. This chapter shows you the ropes.

Chapter 8: “Better Drawing”—Custom drawing is intimidating to many new developers, but it’s a key part of building beautiful and fast user interfaces. You’ll discover the available drawing options from UIKit to Core Graphics, and how to optimize them to look their best while keeping them fast.

Chapter 9: “Layers Like an Onion: Core Animation”—iOS devices have incredible facilities for animation. With a powerful GPU and the highly optimized Core Animation, you can build engaging, exciting, and intuitive interfaces. In this chapter, you go beyond the basics and discover the secrets of animation.

Chapter 10: “Tackling Those Pesky Errors”—You try to write perfect code, but sometimes things go wrong. How your application reacts to the unexpected is what separates decent apps from extraordinary apps. You’ll find the common patterns for error handling, how to log, and how to make your code more resilient against the unexpected.

(New) Chapter 11: “Location Services: Know Where You Are”—Many applications need to know where the user is. While iOS makes this easy, it is important not to drain the battery in the process. You find out how to balance functionality with efficiency and give the user the best possible experience.

Part III: The Right Tool for the Job

There are tools that are part of nearly every application, and there are tools that you only need from time to time. In this section, you learn about the tools and techniques that are a little more specialized.

(New) Chapter 12: “Common UI Paradigms Using Table Views”—Exciting as collection views are, the table view is still the workhorse of iOS. You find out how to take table views beyond the basics with infinite scrolling views and other advanced topics.

(Updated) Chapter 13: “Controlling Multitasking”—Multitasking is an important part of many applications, and you discover how to do multiple things at once while your application is running and when your application is in the background. The new state preservation system of iOS 6 makes this much easier, and you learn how to use it for common situations.

(Updated) Chapter 14: “REST for the Weary”—REST-based services are a mainstay of modern applications, and you learn how to best implement them in iOS.

(Updated) Chapter 15: “Batten the Hatches with Security Services”—User security and privacy are paramount today, and you find out how to protect your application and user data from attackers with the keychain, certificates, and encryption.

Chapter 16: “Running on Multiple iPlatforms and iDevices”—The iOS landscape gets more complex every year with iPod touch, iPhone, iPad, Apple TV, and a steady stream of new editions. It’s not enough just to write once, run everywhere. You need your applications to be their best everywhere. You learn how to adapt your apps to the hardware and get the most out of every platform.

Chapter 17: “Internationalization and Localization”—Although you may want to focus on a single market today, you can do small things to ease the transition to a global market tomorrow. Save money and headaches later, without interrupting today’s development.

Chapter 18: “Selling Past the Sale with In App Purchases”—In App Purchases are still an untapped market for many developers. Users like the add-on content, and developers love the extra revenue. You discover the best ways to make this important feature a reality in your application.

(New) Chapter 19: “Debugging”—If only every application were perfect the first time. Luckily, Xcode and LLDB provide many tools to help you track down even the trickiest of bugs. You go beyond the basics and find out how to deal with errors in development and in the field.

(New) Chapter 20: “Performance Tuning Until It Flies”—Performance separates the “okay” app from the exceptional app. It’s critical to optimizing CPU and memory performance, but you also need to optimize battery and network usage. Apple provides an incredible tool for this in Instruments. You discover how to use Instruments to find the bottlenecks, and then how to improve performance once you find the problems.

Part IV: Pushing the Limits

This section is what this book is all about. You’ve learned the basics. You’ve learned the everyday. Now push the limits with the most advanced tools available. You discover the ins and outs of deep iOS.

(New) Chapter 21: “Storyboards and Custom Transitions”—Storyboards can still be confusing and a bit intimidating for developers familiar with nib files. You learn how to use storyboards to your advantage and how to push them beyond the basics.

Chapter 22: “Cocoa’s Biggest Trick: Key-Value Observing”—Many of Apple’s most powerful frameworks rely on KVO for their performance and flexibility. You find out how to leverage the flexibility and speed of KVO, as well as the trick that makes it so transparent.

Chapter 23: “Think Different: Blocks and Functional Programming”—Many developers are still absorbing the addition of blocks to Objective-C. They’re valuable for interacting with Apple frameworks, but they also open new ways of thinking about your program. Embrace a new style, and maximize its benefits in your next project.

Chapter 24: “Going Offline”—Network programming is difficult, but even harder is providing a seamless offline experience. Discover how to best cache your data and integrate it into your network engine.

(New) Chapter 25: “Data in the Cloud”—Developers are still adapting the new iCloud service. Supporting it quickly can move your app ahead of the pack. You learn your way around this powerful system.

(Updated) Chapter 26: “Fancy Text Layout”—From UIKit to Core Text, iOS is full of ways to display text. iOS adds rich text support throughout UIKit. You find out how to use attributed strings, web views, and Core Text to handle the toughest layout problems.

Chapter 27: “Building a (Core) Foundation”—When you want the most powerful frameworks available on iOS, you’re going to want the Core frameworks like Core Graphics, Core Animation, and Core Text. All of these rely on Core Foundation. In this chapter, you discover how to work Core Foundation data types so you can leverage everything iOS has to offer.

Chapter 28: “Deep Objective-C”—When you’re ready to pull back the curtain on how Objective-C really works, this is the chapter for you. You find out how to use the Objective-C runtime directly to dynamically modify classes and methods. You also learn how Objective-C method calls are dispatched to C function calls, and how you can take control of the system to extend your programs in incredible ways.

You can skip around in this book to focus on the topics you need most. Each chapter stands alone, except for those that require Core Foundation data objects (particularly Core Graphics, Core Animation, and Core Text). Those chapters direct you to Chapter 27, “Building a (Core) Foundation,” when you need that information.

What You Need to Use This Book

All examples in this book were developed with Xcode 4.5 on Mac OS X 10.8 and iOS 6. You need an Apple developer account to access most of the tools and documentation, and you need a developer license to run applications on your iOS device. Visit developer.apple.com/programs/ios to sign up.

Most of the examples in this book will run in the iOS Simulator that comes with Xcode 4.5. You can use the iOS Simulator without an Apple developer license.

Finding Apple Documentation

Apple provides extensive documentation at its website and within Xcode. The URLs change frequently and are often very long. This book refers to Apple documents by title rather than by URL. To find documents in Xcode, press Cmd-Option-? or click Help⇒Documentation and API Reference. In the Documentation Organizer, click the Search icon, type the name of the document, and then select the document from the search results. See Figure 1 for an example of how to search for the Coding Guidelines for Cocoa.

To find documents at the Apple developer site, visit developer.apple.com, click Member Center, and log in. Select the iOS Dev Center, and enter the document title in the Search Developer search box.

The online documentation is generally identical to the Xcode documentation. You may receive results for both iOS and Mac. Be sure to choose the iOS version. Many iOS documents are copies of their Mac counterparts and occasionally include function calls or constants that are not available on iOS. This book tells you which features are available on iOS.

Source Code

As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code files that accompany the book. All of the source code used in this book is available for download at either http://iosptl.com/code or www.wiley.com/go/ptl.ios6programming. For example, you will find the following sample code online in the Chapter 26 folder, in the SimpleLayout project, and the CoreTextLabel.m file.

CoreTextLabel.m (SimpleLayout)

- (id)initWithFrame:(CGRect)frame {

  if ((self = [super initWithFrame:frame])) {

    CGAffineTransform

    transform = CGAffineTransformMakeScale(1, -1);

    CGAffineTransformTranslate(transform,

                               0, -self.bounds.size.height);

    self.transform = transform;

    self.backgroundColor = [UIColor whiteColor];

  }

  return self;

}

9781118449950-fgin01.tif

Figure 1 Searching for Coding Guidelines for Cocoa

Some source code snippets shown in the book are not comprehensive and are meant to help you understand the chapter. For those instances, you can refer to the files available on the website for the complete source code.

Errata

We try to get everything right, but sometimes things change, sometimes we mistype, and sometimes we’re just mistaken. See http://iosptl.com/code for the latest updates, as well as blog posts on topics that haven’t made the book yet. Send any mistakes you find to robnapier@gmail.com and contact@mk.sg.

Part I

What’s New?

Chapter 1 The Brand New Stuff

Chapter 2 Getting Comfortable with Xcode 4 and the LLVM Compiler