iOS开发--线程通信
生活随笔
收集整理的這篇文章主要介紹了
iOS开发--线程通信
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
?
線程間的通信主要用于主線程與子線程的,也有用于子線程與子線程的介紹下面幾種通信方式
1.利用GCD方式(推薦)
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {//開(kāi)一個(gè)子線程dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//下載圖片NSURL *url = [NSURL URLWithString:@"http://e.hiphotos.baidu.com/image/pic/item/14ce36d3d539b600be63e95eed50352ac75cb7ae.jpg"];NSData *data = [NSData dataWithContentsOfURL:url];UIImage *img = [UIImage imageWithData:data];dispatch_async(dispatch_get_main_queue(), ^{//回到主線程self.imgVIew.image = img;});//在這里使用同步還是異步,區(qū)別是前者是按順序依次執(zhí)行,后者是先執(zhí)行到最后再回到主線程N(yùn)SLog(@"________");}); }利用這種方式可以輕松地控制線程間的跳轉(zhuǎn)通信
?
2.利用系統(tǒng)方法
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {//創(chuàng)建子線程[self performSelectorInBackground:@selector(downLoad) withObject:nil]; }//在子線程中下載圖片 - (void)downLoad {NSURL *url = [NSURL URLWithString:@"http://e.hiphotos.baidu.com/image/pic/item/e7cd7b899e510fb34395d1c3de33c895d0430cd1.jpg"];NSData *data = [NSData dataWithContentsOfURL:url];UIImage *img = [UIImage imageWithData:data];//下載完畢,返回給主線程圖片 [self.imgVIew performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:img waitUntilDone:YES];}?
補(bǔ)充:也可以使用
[self performSelectorOnMainThread:@selector(setImg:) withObject:img waitUntilDone:YES];這個(gè)方法返回主線程圖片
@selector(這里面其實(shí)就是主線程中image屬性的set方法)
?
3.使用NSOperation方式
與GCD類似
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {[[[NSOperationQueue alloc] init] addOperationWithBlock:^{//下載圖片NSURL *url = [NSURL URLWithString:@"http://e.hiphotos.baidu.com/image/pic/item/e7cd7b899e510fb34395d1c3de33c895d0430cd1.jpg"];NSData *data = [NSData dataWithContentsOfURL:url];UIImage *img = [UIImage imageWithData:data];//回到主線程[[NSOperationQueue mainQueue] addOperationWithBlock:^{self.imgView.image = img;}];}];}?
轉(zhuǎn)載于:https://www.cnblogs.com/wanghuaijun/p/5326137.html
總結(jié)
以上是生活随笔為你收集整理的iOS开发--线程通信的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: java web图片显示到浏览器
- 下一篇: 二维数组求最大子矩阵的和