在不使用GCD下载情况:


- (void)btnPress:(id)sender{

    self.labContent.text = @"";

    self.indicator.hidden = NO;

    [self.indicator startAnimating];

    

    NSOperationQueue *que = [[NSOperationQueue alloc] init];

    NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(download) object:nil];

    [que addOperation:op];

    self.queue = que;

}


- (void)download{

    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];

    NSError *error;

        NSString *strData = [NSString stringWithContentsOfURL:url

                                                     encoding:NSUTF8StringEncoding

                                                        error:&error];

    if (strData && strData != nil) {

        [self performSelectorOnMainThread:@selector(download_completed:) withObject:strData waitUntilDone:NO];

    }else {

        NSLog(@"error when download:%@", error);

    }

}


- (void)download_completed:(NSString *)strData{

    NSLog(@"call back");

    [self.indicator stopAnimating];

    self.indicator.hidden = YES;

    self.labContent.text = strData;

}



使用GCD后代码简洁多了:


- (void)btnPress:(id)sender{

    self.labContent.text = @"";

    self.indicator.hidden = NO;

    [self.indicator startAnimating];

  

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];

        NSError *error;

        NSString *strData = [NSString stringWithContentsOfURL:url

                                                     encoding:NSUTF8StringEncoding

                                                        error:&error];


        if (strData && strData != nil) {

            dispatch_async(dispatch_get_main_queue(), ^{

                [self.indicator stopAnimating];

                self.indicator.hidden = YES;

                self.labContent.text = strData;

            });

        }else {

            NSLog(@"error when download:%@", error);

        }

    });

}



GCD参考资料:http://mobile.51cto.com/iphone-403490.htm