四.GCDスレッド通信と共通関数
3339 ワード
一.GCDはスレッド間の通信を実現する
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// 1.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 2. URL
NSURL *url = [NSURL URLWithString:@"http://dimg06.c-ctrip.com/images/tg/161/023/909/de45d234ba8147a0ace4880a92c23994_C_640_640.jpg"];
// 3.
NSData *data = [NSData dataWithContentsOfURL:url];
// 4.
UIImage *image = [UIImage imageWithData:data];
NSLog(@"%@", [NSThread currentThread]);
// 5. (UI , )
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"%@", [NSThread currentThread]);
self.imageView.image = image;
});
});
}
二.CGDの一般的な関数
[self performSelector:@selector(task) withObject:nil afterDelay:2];
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(task) userInfo:nil repeats:NO];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
[self task];
NSLog(@"%@", [NSThread currentThread]);
});
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[self task];
});
// 3.
- (void)barrier {
// 1.
dispatch_queue_t queue = dispatch_queue_create("123", DISPATCH_QUEUE_CONCURRENT);
// 2.
dispatch_async(queue, ^{
[self task];
});
dispatch_async(queue, ^{
[self task];
});
// 3.
dispatch_barrier_async(queue, ^{
NSLog(@"-----------------");
});
dispatch_async(queue, ^{
[self task];
});
dispatch_async(queue, ^{
[self task];
});
dispatch_async(queue, ^{
[self task];
});
}