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

CHAPTER 15: Grand Central Dispatch, Background Processing, and You

533

blocks can be defined in-line in your code. You can define a block right at the point where it’s going to be passed to another method or function. Another big difference is that a block can access variables available in the scope where it’s created. By default, the block makes a copy of any variable you access this way, leaving the original intact, but you can make an outside variable “read/write” by prepending the storage qualifier __block before its declaration. Note that there are two underscores before block, not just one.

//define a variable that can be changed by a block __block int a = 0;

//define a block that tries to modify a variable in its scope void (^sillyBlock)(void) = ^{ a = 47; };

//check the value of our variable before calling the block NSLog(@"a == %d", a); // outputs "a == 0"

//execute the block

sillyBlock();

// check the values of our variable again, after calling the block NSLog(@"a == %d", a); // outputs "a == 47"

As we mentioned, blocks really shine when used with GCD, which lets you take a block and add it to a queue in a single step. When you do this with a block that you define immediately at that point, rather than a block stored in a variable, you have the added advantage of being able to see the relevant code directly in the context where it’s being used.

Improving SlowWorker

To see how blocks work, let’s revisit SlowWorker’s doWork: method. It currently looks like this:

- (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]; NSString *resultsSummary = [NSString stringWithFormat:

@"First: [%@]\nSecond: [%@]", firstResult, secondResult];

resultsTextView.text = resultsSummary; NSDate *endTime = [NSDate date]; NSLog(@"Completed in %f seconds",

[endTime timeIntervalSinceDate:startTime]);

}

We can make this method run entirely in the background by wrapping all the code in a block and passing it to a GCD function called dispatch_async. This function takes two parameters: a GCD queue and a block to assign to the queue. Make these two changes

www.it-ebooks.info

534

CHAPTER 15: Grand Central Dispatch, Background Processing, and You

to your copy of doWork:. Be sure to add the closing brace and parenthesis at the end of the method.

- (IBAction)doWork:(id)sender {

NSDate *startTime = [NSDate date]; dispatch_async(dispatch_get_global_queue(0, 0), ^{

NSString *fetchedData = [self fetchSomethingFromServer]; NSString *processedData = [self processData:fetchedData];

NSString *firstResult = [self calculateFirstResult:processedData]; NSString *secondResult = [self calculateSecondResult:processedData]; NSString *resultsSummary = [NSString stringWithFormat:

@"First: [%@]\nSecond: [%@]", firstResult, secondResult];

resultsTextView.text = resultsSummary; NSDate *endTime = [NSDate date]; NSLog(@"Completed in %f seconds",

[endTime timeIntervalSinceDate:startTime]);

});

}

The first line grabs a preexisting global queue that’s always available, using the dispatch_get_global_queue() function. That function takes two arguments: the first lets you specify a priority, and the second is currently unused and should always be 0. If you specify a different priority in the first argument, such as DISPATCH_QUEUE_PRIORITY_HIGH or DISPATCH_QUEUE_PRIORITY_LOW (passing a 0 is the same as passing DISPATCH_QUEUE_PRIORITY_DEFAULT), you will actually get a different global queue, which the system will prioritize differently. For now, we’ll stick with the default global queue.

The queue is then passed to the dispatch_async() function, along with the block of code that comes after. GCD takes that entire block and passes it to a background thread, where it will be executed one step at a time, just as when it was running in the main thread.

Note that we define a variable called startTime just before the block is created, and then use its value at the end of the block. Intuitively, this doesn’t seem to make sense, since by the time the block is executed, the doWork: method has exited, so the NSDate instance that the startTime variable is pointing to should already be released! This is a crucial point of block usage: if a block accesses any variables from “the outside” during its execution, then some special setup happens when the block is created, allowing the block access to those variables. The values contained by such variables will either be duplicated (if they are plain C types such as int or float) or retained (if they are pointers to objects) so that the values they contain can be used inside the block. When dispatch_async is called in the second line of doWork:, and the block shown in the code is created, startTime is actually sent a retain message, whose return value is assigned to what is essentially a new static variable with the same name (startTime) inside the block.

The startTime variable needs to be static inside the block so that code inside the block can’t accidentally mess with a variable that’s defined outside the block. If that were allowed all the time, it would just be confusing for everyone. Sometimes, however, you actually do want to let a block write to a value defined on the outside, and that’s where the __block storage qualifier (which we mentioned a couple of pages ago) comes in

www.it-ebooks.info

CHAPTER 15: Grand Central Dispatch, Background Processing, and You

535

handy. If __block is used to define a variable, then it is directly available to any and all blocks that are defined within the same scope. An interesting side effect of this is that __block-qualified variables are not duplicated or retained when used inside a block.

Don’t Forget That Main Thread

Getting back to the project at hand, there’s one problem here: UIKit thread-safety. Remember that messaging any GUI object, including our resultsTextView, from a background thread is a no-no. Fortunately, GCD provides a way to deal with this, too. Inside the block, we can call another dispatching function, passing work back to the main thread! We do this by once again calling dispatch_async(), this time passing in the queue returned by the dispatch_get_main_queue() function. This always gives us the special queue that lives on the main thread, ready to execute blocks that require the use of the main thread. Make one more change to your version of doWork::

- (IBAction)doWork:(id)sender {

NSDate *startTime = [NSDate date]; dispatch_async(dispatch_get_global_queue(0, 0), ^{

NSString *fetchedData = [self fetchSomethingFromServer]; NSString *processedData = [self processData:fetchedData];

NSString *firstResult = [self calculateFirstResult:processedData]; NSString *secondResult = [self calculateSecondResult:processedData]; NSString *resultsSummary = [NSString stringWithFormat:

@"First: [%@]\nSecond: [%@]", firstResult, secondResult];

dispatch_async(dispatch_get_main_queue(), ^{ resultsTextView.text = resultsSummary;

});

NSDate *endTime = [NSDate date]; NSLog(@"Completed in %f seconds",

[endTime timeIntervalSinceDate:startTime]);

});

}

Giving Some Feedback

If you build and run your app at this point, you’ll see that it now seems to work a bit more smoothly, at least in some sense. The button no longer gets stuck in a highlighted position after you touch it, which perhaps leads you to tap again, and again, and so on. If you look in Xcode’s console log, you’ll see the result of each of those taps, but only the results of the last tap will be shown in the text view.

What we really want to do is enhance the GUI so that after the user presses the button, the display is immediately updated in a way that indicates that an action is underway, and that the button is disabled while the work is in progress. We’ll do this by adding a UIActivityIndicatorView to our display. This class provides the sort of spinner seen in many applications and web sites. Start by declaring it in BIDViewController.h:

@interface BIDViewController : UIViewController

@property (strong, nonatomic) IBOutlet UIButton *startButton;

www.it-ebooks.info

536CHAPTER 15: Grand Central Dispatch, Background Processing, and You

@property (strong, nonatomic) IBOutlet UITextView *resultsTextView;

@property (strong, nonatomic) IBOutlet UIActivityIndicatorView *spinner;

.

.

.

Then open BIDViewController.xib, locate an Activity Indicator View in the library, and drag it into our view, next to the button (see Figure 15–3).

Figure 15–3. Dragging an activity indicator view into our main view in Interface Builder

With the activity indicator spinner selected, use the attributes inspector to check the Hide When Stopped checkbox so that our spinner will appear only when we tell it to start spinning (no one wants an unspinning spinner in their GUI).

Next, control-drag from the File’s Owner icon to the spinner, and connect the spinner outlet. Save your changes.

Now, open BIDViewController.m. Here, we’ll first add the usual code for handling an outlet:

@implementation BIDViewController

@synthesize startButton, resultsTextView;

@synthesize spinner;

www.it-ebooks.info

CHAPTER 15: Grand Central Dispatch, Background Processing, and You

537

.

.

.

- (void)viewDidUnload { [super viewDidUnload];

//Release any retained subviews of the main view.

//e.g. self.myOutlet = nil;

self.startButton = nil; self.resultsTextView = nil; self.spinner = nil;

}

Let’s next work on the doWork: method a bit, adding a few lines to manage the appearance of the button and the spinner when the user clicks and when the work is done. We’ll first set the button’s enabled property to NO, which prevents it from registering any taps but doesn’t give any visual cue. To let the user see that the button is disabled, we’ll set its alpha value to 0.5. You can think of the alpha value as a transparency setting, where 0.0 is fully transparent (that is, invisible) and 1.0 is not transparent at all. We’ll talk more about alpha values in Chapter 16.

- (IBAction)doWork:(id)sender { startButton.enabled = NO; startButton.alpha = 0.5; [spinner startAnimating];

NSDate *startTime = [NSDate date]; dispatch_async(dispatch_get_global_queue(0, 0), ^{

NSString *fetchedData = [self fetchSomethingFromServer]; NSString *processedData = [self processData:fetchedData];

NSString *firstResult = [self calculateFirstResult:processedData]; NSString *secondResult = [self calculateSecondResult:processedData]; NSString *resultsSummary = [NSString stringWithFormat:

@"First: [%@]\nSecond: [%@]", firstResult, secondResult];

dispatch_async(dispatch_get_main_queue(), ^{ startButton.enabled = YES; startButton.alpha = 1.0;

[spinner stopAnimating]; resultsTextView.text = resultsSummary;

});

NSDate *endTime = [NSDate date]; NSLog(@"Completed in %f seconds",

[endTime timeIntervalSinceDate:startTime]);

});

}

Build and run the app, and press the button. That’s more like it, eh? Even though the work being done takes a few seconds, the user isn’t just left hanging. The button is disabled and looks the part as well. Also, the animated spinner lets the user know that the app hasn’t actually hung and can be expected to return to normal at some point.

www.it-ebooks.info

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