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
This edition first published 2013
© 2013 Rob Napier and Mugunth Kumar
Registered office
John Wiley & Sons Ltd, The Atrium, Southern Gate, Chichester, West Sussex, PO19 8SQ, United Kingdom
For details of our global editorial offices, for customer services and for information about how to apply for permission to reuse the copyright material in this book please see our website at www.wiley.com.
The right of the author to be identified as the author of this work has been asserted in accordance with the Copyright, Designs and Patents Act 1988.
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, except as permitted by the UK Copyright, Designs and Patents Act 1988, without the prior permission of the publisher.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.
Designations used by companies to distinguish their products are often claimed as trademarks. All brand names and product names used in this book are trade names, service marks, trademarks or registered trademarks of their respective owners. The publisher is not associated with any product or vendor mentioned in this book. This publication is designed to provide accurate and authoritative information in regard to the subject matter covered. It is sold on the understanding that the publisher is not engaged in rendering professional services. If professional advice or other expert assistance is required, the services of a competent professional should be sought.
Trademarks: Wiley and the Wiley logo are trademarks or registered trademarks of John Wiley & Sons, Inc. Ltd. and/ or its affiliates in the United States and/or other countries, and may not be used without written permission. iPhone, iPad and iPod touch are trademarks of Apple Inc. All trademarks are the property of their respective owners. John Wiley & Sons, Ltd. is not associated with any product or vendor mentioned in the book.
ISBN 978-1-118-44995-0 (pbk); ISBN 978-1-118-44996-7 (ebk); ISBN 978-1-118-44997-4 (ebk); ISBN 978-1-118-44998-1 (ebk)
A catalogue record for this book is available from the British Library.
Printed in United States by Bind-Rite
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 lifeMugunth
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.