- •Contents at a Glance
- •About the Authors
- •About the Technical Reviewer
- •Acknowledgments
- •Preface
- •What This Book Is
- •What You Need
- •Developer Options
- •What You Need to Know
- •What’s Different About Coding for iOS?
- •Only One Active Application
- •Only One Window
- •Limited Access
- •Limited Response Time
- •Limited Screen Size
- •Limited System Resources
- •No Garbage Collection, but…
- •Some New Stuff
- •A Different Approach
- •What’s in This Book
- •What’s New in This Update?
- •Are You Ready?
- •Setting Up Your Project in Xcode
- •The Xcode Workspace Window
- •The Toolbar
- •The Navigator View
- •The Jump Bar
- •The Utility Pane
- •Interface Builder
- •New Compiler and Debugger
- •A Closer Look at Our Project
- •Introducing Xcode’s Interface Builder
- •What’s in the Nib File?
- •The Library
- •Adding a Label to the View
- •Changing Attributes
- •Some iPhone Polish—Finishing Touches
- •Bring It on Home
- •The Model-View-Controller Paradigm
- •Creating Our Project
- •Looking at the View Controller
- •Understanding Outlets and Actions
- •Outlets
- •Actions
- •Cleaning Up the View Controller
- •Designing the User Interface
- •Adding the Buttons and Action Method
- •Adding the Label and Outlet
- •Writing the Action Method
- •Trying It Out
- •Looking at the Application Delegate
- •Bring It on Home
- •A Screen Full of Controls
- •Active, Static, and Passive Controls
- •Creating the Application
- •Implementing the Image View and Text Fields
- •Adding the Image View
- •Resizing the Image View
- •Setting View Attributes
- •The Mode Attribute
- •Interaction Checkboxes
- •The Alpha Value
- •Background
- •Drawing Checkboxes
- •Stretching
- •Adding the Text Fields
- •Text Field Inspector Settings
- •Setting the Attributes for the Second Text Field
- •Creating and Connecting Outlets
- •Closing the Keyboard
- •Closing the Keyboard When Done Is Tapped
- •Touching the Background to Close the Keyboard
- •Adding the Slider and Label
- •Creating and Connecting the Actions and Outlets
- •Implementing the Action Method
- •Adding Two Labeled Switches
- •Connecting and Creating Outlets and Actions
- •Implementing the Switch Actions
- •Adding the Button
- •Connecting and Creating the Button Outlets and Actions
- •Implementing the Segmented Control Action
- •Implementing the Action Sheet and Alert
- •Conforming to the Action Sheet Delegate Method
- •Showing the Action Sheet
- •Spiffing Up the Button
- •Using the viewDidLoad Method
- •Control States
- •Stretchable Images
- •Crossing the Finish Line
- •The Mechanics of Autorotation
- •Points, Pixels, and the Retina Display
- •Autorotation Approaches
- •Handling Rotation Using Autosize Attributes
- •Configuring Supported Orientations
- •Specifying Rotation Support
- •Designing an Interface with Autosize Attributes
- •Using the Size Inspector’s Autosize Attributes
- •Setting the Buttons’ Autosize Attributes
- •Restructuring a View When Rotated
- •Creating and Connecting Outlets
- •Moving the Buttons on Rotation
- •Swapping Views
- •Designing the Two Views
- •Implementing the Swap
- •Changing Outlet Collections
- •Rotating Out of Here
- •Common Types of Multiview Apps
- •The Architecture of a Multiview Application
- •The Root Controller
- •Anatomy of a Content View
- •Building View Switcher
- •Creating Our View Controller and Nib Files
- •Modifying the App Delegate
- •Modifying BIDSwitchViewController.h
- •Adding a View Controller
- •Building a View with a Toolbar
- •Writing the Root View Controller
- •Implementing the Content Views
- •Animating the Transition
- •Switching Off
- •The Pickers Application
- •Delegates and Data Sources
- •Setting Up the Tab Bar Framework
- •Creating the Files
- •Adding the Root View Controller
- •Creating TabBarController.xib
- •The Initial Test Run
- •Implementing the Date Picker
- •Implementing the Single-Component Picker
- •Declaring Outlets and Actions
- •Building the View
- •Implementing the Controller As a Data Source and Delegate
- •Implementing a Multicomponent Picker
- •Declaring Outlets and Actions
- •Building the View
- •Implementing the Controller
- •Implementing Dependent Components
- •Creating a Simple Game with a Custom Picker
- •Writing the Controller Header File
- •Building the View
- •Adding Image Resources
- •Implementing the Controller
- •The spin Method
- •The viewDidLoad Method
- •Final Details
- •Linking in the Audio Toolbox Framework
- •Final Spin
- •Table View Basics
- •Table Views and Table View Cells
- •Grouped and Plain Tables
- •Implementing a Simple Table
- •Designing the View
- •Writing the Controller
- •Adding an Image
- •Using Table View Cell Styles
- •Setting the Indent Level
- •Handling Row Selection
- •Changing the Font Size and Row Height
- •Customizing Table View Cells
- •Adding Subviews to the Table View Cell
- •Creating a UITableViewCell Subclass
- •Adding New Cells
- •Implementing the Controller’s Code
- •Loading a UITableViewCell from a Nib
- •Designing the Table View Cell in Interface Builder
- •Using the New Table View Cell
- •Grouped and Indexed Sections
- •Building the View
- •Importing the Data
- •Implementing the Controller
- •Adding an Index
- •Implementing a Search Bar
- •Rethinking the Design
- •A Deep Mutable Copy
- •Updating the Controller Header File
- •Modifying the View
- •Modifying the Controller Implementation
- •Copying Data from allNames
- •Implementing the Search
- •Changes to viewDidLoad
- •Changes to Data Source Methods
- •Adding a Table View Delegate Method
- •Adding Search Bar Delegate Methods
- •Adding a Magnifying Glass to the Index
- •Adding the Special Value to the Keys Array
- •Suppressing the Section Header
- •Telling the Table View What to Do
- •Putting It All on the Table
- •Navigation Controller Basics
- •Stacky Goodness
- •A Stack of Controllers
- •Nav, a Hierarchical Application in Six Parts
- •Meet the Subcontrollers
- •The Disclosure Button View
- •The Checklist View
- •The Rows Control View
- •The Movable Rows View
- •The Deletable Rows View
- •The Editable Detail View
- •The Nav Application’s Skeleton
- •Creating the Top-Level View Controller
- •Setting Up the Navigation Controller
- •Adding the Images to the Project
- •First Subcontroller: The Disclosure Button View
- •Creating the Detail View
- •Modifying the Disclosure Button Controller
- •Adding a Disclosure Button Controller Instance
- •Second Subcontroller: The Checklist
- •Creating the Checklist View
- •Adding a Checklist Controller Instance
- •Third Subcontroller: Controls on Table Rows
- •Creating the Row Controls View
- •Adding a Rows Control Controller Instance
- •Fourth Subcontroller: Movable Rows
- •Creating the Movable Row View
- •Adding a Move Me Controller Instance
- •Fifth Subcontroller: Deletable Rows
- •Creating the Deletable Rows View
- •Adding a Delete Me Controller Instance
- •Sixth Subcontroller: An Editable Detail Pane
- •Creating the Data Model Object
- •Creating the Detail View List Controller
- •Creating the Detail View Controller
- •Adding an Editable Detail View Controller Instance
- •But There’s One More Thing. . .
- •Breaking the Tape
- •Creating a Simple Storyboard
- •Dynamic Prototype Cells
- •Dynamic Table Content, Storyboard-Style
- •Editing Prototype Cells
- •Good Old Table View Data Source
- •Will It Load?
- •Static Cells
- •Going Static
- •So Long, Good Old Table View Data Source
- •You Say Segue, I Say Segue
- •Creating Segue Navigator
- •Filling the Blank Slate
- •First Transition
- •A Slightly More Useful Task List
- •Viewing Task Details
- •Make More Segues, Please
- •Passing a Task from the List
- •Handling Task Details
- •Passing Back Details
- •Making the List Receive the Details
- •If Only We Could End with a Smooth Transition
- •Split Views and Popovers
- •Creating a SplitView Project
- •The Storyboard Defines the Structure
- •The Code Defines the Functionality
- •The App Delegate
- •The Master View Controller
- •The Detail View Controller
- •Here Come the Presidents
- •Creating Your Own Popover
- •iPad Wrap-Up
- •Getting to Know Your Settings Bundle
- •The AppSettings Application
- •Creating the Project
- •Working with the Settings Bundle
- •Adding a Settings Bundle to Our Project
- •Setting Up the Property List
- •Adding a Text Field Setting
- •Adding an Application Icon
- •Adding a Secure Text Field Setting
- •Adding a Multivalue Field
- •Adding a Toggle Switch Setting
- •Adding the Slider Setting
- •Adding Icons to the Settings Bundle
- •Adding a Child Settings View
- •Reading Settings in Our Application
- •Retrieving User Settings
- •Creating the Main View
- •Updating the Main View Controller
- •Registering Default Values
- •Changing Defaults from Our Application
- •Keeping It Real
- •Beam Me Up, Scotty
- •Your Application’s Sandbox
- •Getting the Documents Directory
- •Getting the tmp Directory
- •File-Saving Strategies
- •Single-File Persistence
- •Multiple-File Persistence
- •Using Property Lists
- •Property List Serialization
- •The First Version of the Persistence Application
- •Creating the Persistence Project
- •Designing the Persistence Application View
- •Editing the Persistence Classes
- •Archiving Model Objects
- •Conforming to NSCoding
- •Implementing NSCopying
- •Archiving and Unarchiving Data Objects
- •The Archiving Application
- •Implementing the BIDFourLines Class
- •Implementing the BIDViewController Class
- •Using iOS’s Embedded SQLite3
- •Creating or Opening the Database
- •Using Bind Variables
- •The SQLite3 Application
- •Linking to the SQLite3 Library
- •Modifying the Persistence View Controller
- •Using Core Data
- •Entities and Managed Objects
- •Key-Value Coding
- •Putting It All in Context
- •Creating New Managed Objects
- •Retrieving Managed Objects
- •The Core Data Application
- •Designing the Data Model
- •Creating the Persistence View and Controller
- •Persistence Rewarded
- •Managing Document Storage with UIDocument
- •Building TinyPix
- •Creating BIDTinyPixDocument
- •Code Master
- •Initial Storyboarding
- •Creating BIDTinyPixView
- •Storyboard Detailing
- •Adding iCloud Support
- •Creating a Provisioning Profile
- •Enabling iCloud Entitlements
- •How to Query
- •Save Where?
- •Storing Preferences on iCloud
- •What We Didn’t Cover
- •Grand Central Dispatch
- •Introducing SlowWorker
- •Threading Basics
- •Units of Work
- •GCD: Low-Level Queueing
- •Becoming a Blockhead
- •Improving SlowWorker
- •Don’t Forget That Main Thread
- •Giving Some Feedback
- •Concurrent Blocks
- •Background Processing
- •Application Life Cycle
- •State-Change Notifications
- •Creating State Lab
- •Exploring Execution States
- •Making Use of Execution State Changes
- •Handling the Inactive State
- •Handling the Background State
- •Removing Resources When Entering the Background
- •Saving State When Entering the Background
- •A Brief Journey to Yesteryear
- •Back to the Background
- •Requesting More Backgrounding Time
- •Grand Central Dispatch, Over and Out
- •Two Views of a Graphical World
- •The Quartz 2D Approach to Drawing
- •Quartz 2D’s Graphics Contexts
- •The Coordinate System
- •Specifying Colors
- •A Bit of Color Theory for Your iOS Device’s Display
- •Other Color Models
- •Color Convenience Methods
- •Drawing Images in Context
- •Drawing Shapes: Polygons, Lines, and Curves
- •The QuartzFun Application
- •Setting Up the QuartzFun Application
- •Creating a Random Color
- •Defining Application Constants
- •Implementing the QuartzFunView Skeleton
- •Creating and Connecting Outlets and Actions
- •Implementing the Action Methods
- •Adding Quartz 2D Drawing Code
- •Drawing the Line
- •Drawing the Rectangle and Ellipse
- •Drawing the Image
- •Optimizing the QuartzFun Application
- •The GLFun Application
- •Setting Up the GLFun Application
- •Creating BIDGLFunView
- •Updating BIDViewController
- •Updating the Nib
- •Finishing GLFun
- •Drawing to a Close
- •Multitouch Terminology
- •The Responder Chain
- •Responding to Events
- •Forwarding an Event: Keeping the Responder Chain Alive
- •The Multitouch Architecture
- •The Four Touch Notification Methods
- •The TouchExplorer Application
- •The Swipes Application
- •Automatic Gesture Recognition
- •Implementing Multiple Swipes
- •Detecting Multiple Taps
- •Detecting Pinches
- •Defining Custom Gestures
- •The CheckPlease Application
- •The CheckPlease Touch Methods
- •Garçon? Check, Please!
- •The Location Manager
- •Setting the Desired Accuracy
- •Setting the Distance Filter
- •Starting the Location Manager
- •Using the Location Manager Wisely
- •The Location Manager Delegate
- •Getting Location Updates
- •Getting Latitude and Longitude Using CLLocation
- •Error Notifications
- •Trying Out Core Location
- •Updating Location Manager
- •Determining Distance Traveled
- •Wherever You Go, There You Are
- •Accelerometer Physics
- •Don’t Forget Rotation
- •Core Motion and the Motion Manager
- •Event-Based Motion
- •Proactive Motion Access
- •Accelerometer Results
- •Detecting Shakes
- •Baked-In Shaking
- •Shake and Break
- •Accelerometer As Directional Controller
- •Rolling Marbles
- •Writing the Ball View
- •Calculating Ball Movement
- •Rolling On
- •Using the Image Picker and UIImagePickerController
- •Implementing the Image Picker Controller Delegate
- •Road Testing the Camera and Library
- •Designing the Interface
- •Implementing the Camera View Controller
- •It’s a Snap!
- •Localization Architecture
- •Strings Files
- •What’s in a Strings File?
- •The Localized String Macro
- •Real-World iOS: Localizing Your Application
- •Setting Up LocalizeMe
- •Trying Out LocalizeMe
- •Localizing the Nib
- •Localizing an Image
- •Generating and Localizing a Strings File
- •Localizing the App Display Name
- •Auf Wiedersehen
- •Apple’s Documentation
- •Mailing Lists
- •Discussion Forums
- •Web Sites
- •Blogs
- •Conferences
- •Follow the Authors
- •Farewell
- •Index
522 |
CHAPTER 14: Hey! You! Get onto iCloud! |
NSUbiquitousKeyValueStore *prefs = [NSUbiquitousKeyValueStore defaultStore]; NSInteger selectedColorIndex = [prefs longLongForKey:@"selectedColorIndex"]; self.colorControl.selectedSegmentIndex = selectedColorIndex;
}
We also need to make a change to the detail display, so that it will pick up the color from the correct place. Select BIDDetailViewController.m, find the configureView method, and change its last few lines as shown here:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; self.selectedColorIndex = [prefs integerForKey:@"selectedColorIndex"];
NSUbiquitousKeyValueStore *prefs = [NSUbiquitousKeyValueStore defaultStore]; self.selectedColorIndex = [prefs longLongForKey:@"selectedColorIndex"];
That’s it! You can now run the app on multiple devices configured for the same iCloud user, and will see that setting the color on one device results in the new color appearing on the other device the next time a document is opened there. Piece of cake!
What We Didn’t Cover
We now have the basics of an iCloud-enabled, document-based application up and running, but there are a few more issues that you may want to consider. We’re not going to cover these topics in this book, but if you’re serious about making a great iCloudbased app, you’ll want to think about these areas:
Documents stored in iCloud are prone to conflicts. What happens if you edit the same TinyPix file on several devices at once? Fortunately, Apple has already thought of this, and provides some ways to deal with these conflicts in your app. It’s up to you to decide if you want to ignore conflicts, try to fix them automatically, or ask the user to help sort out the problem. For full details, search for “resolving document version conflicts” in the Xcode documentation viewer.
Apple recommends that you design your application to work in a completely offline mode in case the user isn’t using iCloud for some reason. It also recommends that you provide a way for a user to move files between iCloud storage and local storage. Sadly, Apple doesn’t provide or suggest any standard GUI for helping a user manage this, and current apps that provide this functionality, such as Apple’s iWork apps, don’t seem to handle it in a particularly user-friendly way. See Apple’s “Managing the Life Cycle of a Document” in the Xcode documentation for more on this.
Apple supports using iCloud for Core Data storage, and even provides a class called UIManagedDocument that you can subclass if you want to make that work. See the UIManagedDocument class reference for more information, or take a look at More iOS 5 Development: Further Explorations of the iOS SDK, (http://apress.com/book/ view/1430232528) by Dave Mark, Alex Horowitz, Kevin Kim, and Jeff
www.it-ebooks.info
CHAPTER 14: Hey! You! Get onto iCloud! |
523 |
LaMarche (Apress, 2012) for a hands-on guide to building an iCloudbacked Core Data app.
What’s up next? In Chapter 15, we’ll take you through the process of having your apps work properly in a multithreaded, multitasking environment.
www.it-ebooks.info
Chapter 15
Grand Central Dispatch,
Background Processing,
and You
If you’ve ever tried your hand at multithreaded programming, in any environment, chances are you’ve come away from the experience with a feeling of dread, terror, or worse. Fortunately, technology marches on, and lately Apple has come up with a new approach that makes multithreaded programming much easier. This approach is called Grand Central Dispatch, and we’ll get you started using it in this chapter. We’ll also dig into the multitasking capabilities of iOS, showing you how to adjust your applications to play nicely in this new world, as well as using the new capabilities to make your apps work even better than before.
Grand Central Dispatch
One of the biggest challenges facing developers today is to write software that can perform complex actions in response to user input while remaining responsive so that the user isn’t constantly kept waiting while the processor does some behind-the-scenes task. If you think about it, that challenge has been with us all along, and in spite of the advances in computing technology that bring us faster CPUs, the problem persists. If you want evidence, you need look no further than your nearest computer screen. Chances are that the last time you sat down to work at your computer, at some point, your work flow was interrupted by a spinning mouse cursor of some kind or another.
So why does this continue to vex us, given all the advances in system architecture? One part of the problem is the way that software is typically written: as a sequence of events to be performed in order. Such software can scale up as CPU speeds increase, but only to a certain point. As soon as the program gets stuck waiting for an external resource, such as a file or a network connection, the entire sequence of events is effectively paused. All modern operating systems now allow the use of multiple threads of
D.Mark et al., Beginning iOS 5 Development
©Dave Mark, Jack Nutting, Jeff LaMarche 2011
www.it-ebooks.info
526 |
CHAPTER 15: Grand Central Dispatch, Background Processing, and You |
execution within a program, so that even if a single thread is stuck waiting for a specific event, the other threads can keep going. Even so, many developers see multithreaded programming as something of a black art and shy away from it.
Fortunately, Apple has some good news for anyone who wants to break up their code into simultaneous chunks without too much hands-on intimacy with the system’s threading layer. This good news is called Grand Central Dispatch (GCD). It provides an entirely new API for splitting up the work your application needs to do into smaller chunks that can be spread across multiple threads and, with the right hardware, multiple CPUs.
Much of this new API is accessed using blocks, another Apple innovation that adds a sort of anonymous in-line function capability to C and Objective-C. Blocks have a lot in common with similar features in languages such as Ruby and Lisp, and they can provide interesting new ways to structure interactions between different objects while keeping related code closer together in your methods.
Introducing SlowWorker
As a platform for demonstrating how GCD works, we’ll create an application called SlowWorker, which consists of a simple interface driven by a single button and a text view. Click the button, and a synchronous task is immediately started, locking up the app for about ten seconds. Once the task completes, some text appears in the text view (see Figure 15–1).
Figure 15–1. The SlowWorker application hides its interface behind a single button. Click the button, and the interface hangs for about ten seconds while the application does its work.
www.it-ebooks.info
CHAPTER 15: Grand Central Dispatch, Background Processing, and You |
527 |
Start by using the Single View Application template to make a new application in Xcode, as you’ve done many times before. Name this one SlowWorker, set Device Family to iPhone, and turn off the Use Storyboard option. Make the following additions to
BIDViewController.h:
#import <UIKit/UIKit.h>
@interface BIDViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIButton *startButton; @property (strong, nonatomic) IBOutlet UITextView *resultsTextView;
- (IBAction)doWork:(id)sender;
@end
This simply defines a couple of outlets to the two objects visible in our GUI and an action method to be triggered by the button.
Now, enter the following code near the top of BIDViewController.m:
#import "BIDViewController.h"
@implementation BIDViewController
@synthesize startButton, resultsTextView;
- (NSString *)fetchSomethingFromServer { [NSThread sleepForTimeInterval:1]; return @"Hi there";
}
- (NSString *)processData:(NSString *)data { [NSThread sleepForTimeInterval:2]; return [data uppercaseString];
}
- (NSString *)calculateFirstResult:(NSString *)data { [NSThread sleepForTimeInterval:3];
return [NSString stringWithFormat:@"Number of chars: %d", [data length]];
}
- (NSString *)calculateSecondResult:(NSString *)data { [NSThread sleepForTimeInterval:4];
return [data stringByReplacingOccurrencesOfString:@"E" withString:@"e"];
}
- (IBAction)doWork:(id)sender {
NSDate *startTime = [NSDate date];
NSString *fetchedData = [self fetchSomethingFromServer]; NSString *processedData = [self processData:fetchedData];
NSString *firstResult = [self calculateFirstResult:processedData]; NSString *secondResult = [self calculateSecondResult:processedData];
www.it-ebooks.info
528 CHAPTER 15: Grand Central Dispatch, Background Processing, and You
NSString *resultsSummary = [NSString stringWithFormat:
@"First: [%@]\nSecond: [%@]", firstResult, secondResult];
resultsTextView.text = resultsSummary; NSDate *endTime = [NSDate date]; NSLog(@"Completed in %f seconds",
[endTime timeIntervalSinceDate:startTime]);
}
.
.
.
Next, add the usual cleanup code in viewDidUnload:
- (void)viewDidUnload { [self viewDidUnload];
//Release any retained subviews of the main view.
//e.g. self.myOutlet = nil;
self.startButton = nil; self.resultsTextView = nil;
}
As you can see, the work of this class (such as it is) is split up into a number of small chunks. This code is just meant to simulate some slow activities, and none of those methods really do anything time-consuming at all. To make things interesting, each method contains a call to the sleepForTimeInterval: class method in NSThread, which simply makes the program (specifically, the thread from which the method is called) effectively pause and do nothing at all for the given number of seconds. The doWork: method also contains code at the beginning and end to calculate the amount of time it took for all the work to be done.
Now, open BIDViewController.xib, and drag a Round Rect Button and a Text View into the empty View window, laying things out as shown in Figure 15–2. Control-drag from File’s Owner to connect the view controller’s two outlets to the button and the text view.
Next, select the button, and go to the connections inspector to connect the button’s Touch Up Inside event to File’s Owner, selecting the view controller’s doWork: method. Finally, select the text view, use the attributes inspector to uncheck the Editable checkbox (it’s in the upper-right corner), and delete the default text from the text view.
www.it-ebooks.info
CHAPTER 15: Grand Central Dispatch, Background Processing, and You |
529 |
Figure 15–2. The SlowWorker interface consists of a round rect button and a text view. Be sure to uncheck the Editable checkbox for the text view and delete all of its text.
Save your work. Then select Run. Your app should start up, and pressing the button will make it work for about ten seconds (the sum of all those sleep amounts) before showing you the results. During your wait, you’ll see that the Start Working! button remains dark blue the entire time, never turning back to its normal color until the “work” is done. Also, until the work is complete, the application’s view is unresponsive. Tapping anywhere on the screen has no effect. In fact, the only way you can interact with your application during this time is by tapping the home button to switch away from it. This is exactly the state of affairs we want to avoid!
In this particular case, the wait is not too bad, since the application appears to be hung for just a few seconds, but if your app regularly hangs this way for much longer, using it will be a frustrating experience. In the worst of cases, the operating system may actually kill your app if it’s unresponsive for too long. In any case, you’ll end up with some unhappy users—and maybe even some ex-users!
www.it-ebooks.info