码迷,mamicode.com
首页 > 其他好文 > 详细

GCD工作单元

时间:2016-05-18 17:35:36      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

#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

 

GCD工作单元

标签:

原文地址:http://www.cnblogs.com/linxiu-0925/p/5505873.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!