Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Beginning iOS5 Development.pdf
Скачиваний:
7
Добавлен:
09.05.2015
Размер:
15.6 Mб
Скачать

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

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]