标签:
#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
标签:
原文地址:http://www.cnblogs.com/linxiu-0925/p/5505873.html