在这里,简单介绍下GCD的应用。
1.编程场景 :
在iPhone上做一个下载图片的功能,很简单,就是在屏幕上放置一个按钮,点击该按钮,显示一个转动的圆圈,表示正在下载,下载完成后,将图片显示出来。
2.主要代码如下:
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic,strong) UIActivityIndicatorView *indicator; // 指示视图
@property (nonatomic,strong) UIImageView *imgV; // 显示图片
@property (nonatomic,strong) UIButton *btn; // 点击按钮
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.view addSubview:self.btn];
}
-(UIActivityIndicatorView *)indicator {
if (_indicator == nil) {
_indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
_indicator.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.width);
_indicator.backgroundColor = [UIColor lightGrayColor];
}
[self.view addSubview:_indicator];
return _indicator;
}
-(UIImageView *)imgV {
if (_imgV == nil) {
_imgV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 230, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.width)];
_imgV.backgroundColor = [UIColor blueColor];
}
[self.view addSubview:_imgV];
return _imgV;
}
-(UIButton *)btn {
if (_btn == nil) {
_btn = [UIButton buttonWithType:UIButtonTypeCustom];
_btn.frame = CGRectMake(10, 50, 200, 50);
_btn.backgroundColor = [UIColor redColor];
[_btn setTitle:@"点击加载图片" forState:UIControlStateNormal];
[_btn addTarget:self action:@selector(loadImage) forControlEvents:UIControlEventTouchUpInside];
}
return _btn;
}
/** 加载图片 */
-(void)loadImage {
self.indicator.hidden = NO;
[self.indicator startAnimating];
[self.imgV addSubview:self.indicator];
// 开启一个线程进行数据请求
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *url1 = [NSURL URLWithString:@"http://pic.qiantucdn.com/58pic/18/32/08/32658PICPUs_1024.png"];
NSError *error;
NSData *data = [NSData dataWithContentsOfURL:url1];
if (data != nil) {
// 在主线程中完成UI操作
dispatch_async(dispatch_get_main_queue(), ^{
[self.indicator stopAnimating];
self.indicator.hidden = YES;
UIImage *image = [UIImage imageWithData:data];
self.imgV.image = image;
});
}else {
NSLog(@"error whin download:%@",error);
}
});
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end