標籤:
//// ViewController.m// Begin iOS7 GCD//// Created by zyz on 15-4-1.// Copyright (c) 2015年 Apple. All rights reserved.//#import "ViewController.h"@interface ViewController ()//storyboard三個控制項@property (weak, nonatomic) IBOutlet UIButton *startButton;@property (weak, nonatomic) IBOutlet UILabel *resultTextView;@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *spinner;@end@implementation ViewController- (NSString *)fetchSomethingFromServer{ [NSThread sleepForTimeInterval:1]; return @"Hi, Here";}- (NSString *)processData:(NSString *)data{ [NSThread sleepForTimeInterval:2]; return [data uppercaseString];}- (NSString *)calculateFirstResult:(NSString *)data{ [NSThread sleepForTimeInterval:3]; return [NSString stringWithFormat:@"Number of chars: %lu", (unsigned long)[data length]];}- (NSString *)calculateSecondResult:(NSString *)data{ [NSThread sleepForTimeInterval:4]; return [data stringByReplacingOccurrencesOfString:@"E" withString:@"e"];}//點擊事件- (IBAction)buttonClick:(id)sender { self.startButton.enabled = NO; [self.spinner setHidden:NO]; [self.spinner startAnimating]; dispatch_queue_t queue1 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(queue1, ^{ NSLog(@"queue1 Thread is %@",[NSThread currentThread]); NSDate *startTime = [NSDate date]; NSString *fetchedDate = [self fetchSomethingFromServer]; NSString *processDate = [self processData:fetchedDate]; NSString *firstResult = [self calculateFirstResult:processDate]; NSString *secondResult = [self calculateSecondResult:processDate]; dispatch_queue_t queue2 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_queue_t queue3 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); //注意字串只定義,不會為字串分配空間,追加字串會失敗,這裡定義為空白的正確方式 __block NSString *resultsSummary = [NSString stringWithFormat:@""]; //非同步載入,可能還沒有執行完成就執行主線程的非同步載入 dispatch_async(queue2, ^{ resultsSummary = [NSString stringWithFormat:@"First:[%@]\n",firstResult]; NSLog(@"queue2 Thread is %@",[NSThread currentThread]); }); dispatch_async(queue3, ^{ resultsSummary = [resultsSummary stringByAppendingString:[NSString stringWithFormat:@"Second:[%@]",secondResult]]; NSLog(@"queue3 Thread is %@",[NSThread currentThread]); }); dispatch_async(dispatch_get_main_queue(), ^{ //這裡字串仍然為空白,因為非同步載入執行的語句還沒有完成就到了這裡 resultsSummary = [resultsSummary stringByAppendingString:@"1111"]; //label的內容是1111,或者是其他的可能結果 self.resultTextView.text = resultsSummary; self.resultTextView.backgroundColor = [UIColor brownColor]; [self.spinner stopAnimating]; [self.spinner setHidden:YES]; }); NSDate *endTime = [NSDate date]; NSLog(@"Completed in %f seconds",[endTime timeIntervalSinceDate:startTime]); });}- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [self.spinner setHidden:YES];}- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}@end
Begin iOS7 GCD