您的位置:首页 > 其它

GCD工作单元

2016-05-18 17:08 369 查看
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (weak,nonatomic)IBOutlet UIButton *startBtn;
@property (weak,nonatomic)IBOutlet UITextView *resultsTextView;
@property (weak,nonatomic)IBOutlet UIActivityIndicatorView *spinner;

@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

-(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:%lu",(unsigned long)[data length]];
}

-(NSString *)calculateSecondResult:(NSString *)data{
[NSThread sleepForTimeInterval:4];
return [data stringByReplacingOccurrencesOfString:@"E" withString:@"e"];
}

-(IBAction)doWork:(id)sender{

NSDate *startTime = [NSDate date];
//添加指示器代码
self.startBtn.enabled = NO;

[self.spinner startAnimating];

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{

NSString *fetchedData = [self fetchSomethingFromServer];
NSString *processedData = [self processData:fetchedData];
NSString *firstResult = [self calculateFirstResult:processedData];
NSString *senconResult = [self calculateSecondResult:processedData];
NSString *resultSummary = [NSString stringWithFormat:@"First:[%@]\nSecond:[%@]",firstResult,senconResult];

dispatch_async(dispatch_get_main_queue(), ^{

self.resultsTextView.text = resultSummary;
});

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

});

// 1 NSString *fetchedData = [self fetchSomethingFromServer];
// NSString *processedData = [self processData:fetchedData];
// NSString *firstResult = [self calculateFirstResult:processedData];
// NSString *senconResult = [self calculateSecondResult:processedData];
// NSString *resultSummary = [NSString stringWithFormat:@"First:[%@]\nSecond:[%@]",firstResult,senconResult];

// self.resultsTextView.text = resultSummary;
// NSDate *endTime = [NSDate date];
// NSLog(@"Completed in %f seconds",[endTime timeIntervalSinceDate:startTime]);
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: