博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
IOS多线程 - 使用线程加载一张图片 - NSThread(1)
阅读量:7208 次
发布时间:2019-06-29

本文共 1871 字,大约阅读时间需要 6 分钟。

更新UI的操作在IOS中其实和在Android中是一致的,都是不能在主线程中执行比较耗时的操作,所以需要开启新线程去做这些操作,以免阻塞主线程,当新线程中的操作完成之后,调用主线程来更新UI。下面就是一个这样的例子:

1、声明ImageView控件

1 #import 
2 3 @interface DemoDispatchQueueViewController : UIViewController4 @property(nonatomic,strong) UIImageView *imageView;5 @end

2、完成功能

1 #import "DemoDispatchQueueViewController.h" 2  3 @interface DemoDispatchQueueViewController () 4  5 @end 6  7 @implementation DemoDispatchQueueViewController 8 @synthesize imageView; 9 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil10 {11     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];12     if (self) {13     }14     return self;15 }16 17 - (void)viewDidLoad18 {19     [super viewDidLoad];20     // Do any additional setup after loading the view.21     self.title = @"GCD Demo";22     23     self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 300, 380)];24     25     self.imageView.contentMode = UIViewContentModeScaleToFill;26     27     [self.view addSubview:imageView];28     29     [NSThread detachNewThreadSelector:@selector(loadImageByUrl:) toTarget:self withObject:@"http://image.rayliimg.cn/0008/2009-01-15/images/2009115135825184.jpg"];30     31 }32 33 -(void) loadImageByUrl:(NSString *) imageUrl34 {35     NSLog(@"url is :%@",imageUrl);36     NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];37     UIImage *image = [UIImage imageWithData:data];38     39     if(image != nil){40         [self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];41     }else{42         NSLog(@"无法载入相应的图片");43     }44 }45 -(void) setImage:(UIImage*) image{46     [self.imageView setImage:image];47 }48 49 50 - (void)didReceiveMemoryWarning51 {52     [super didReceiveMemoryWarning];53     // Dispose of any resources that can be recreated.54 }55 56 @end

 

 

转载地址:http://qkoum.baihongyu.com/

你可能感兴趣的文章
ZJOI2008皇帝的烦恼
查看>>
新手windows安装nginx
查看>>
浏览器兼容问题踩坑收集
查看>>
Python 实用技巧
查看>>
object c中@property 的使用
查看>>
Sping 核心IOC容器
查看>>
poj 2524
查看>>
MapReduce
查看>>
论文阅读笔记五十六:(ExtremeNet)Bottom-up Object Detection by Grouping Extreme and Center Points(CVPR2019)...
查看>>
回收期计算
查看>>
response响应
查看>>
10 个十分难得的 javascript 开发经验
查看>>
Common Subsequence
查看>>
【CSS3】标签使用说明
查看>>
n皇后问题—回溯法 C++实现
查看>>
on delete cascade
查看>>
Connected Graph
查看>>
openfile iscisi 配置
查看>>
SCAU 9504 面试
查看>>
基本数据类型、输入输出、运算符
查看>>