zoukankan      html  css  js  c++  java
  • 05-线程间通讯

    线程间通讯


    • 从网络中下载一张图片放入到UIImageView中
    - (void)touchBegin:(NSSet *)touches withEvent:(UIEvent *)event
    {
    	//1.下载图片
    	/*
    	//测试执行时间
    	//NSDate *begin = [NSDate date];
    	CFAbsoluteTime begin = CFAbsoluterTimeGetCurrent();
    	
    	//从网络下载一张图片
    	NSURL *url = [NSURL URLWihtString:@"图片资源网址"];
    	NSData *data = [NSData dataWithContentsOfURL:url];//耗时,应开启子线程
    	
    	//NSDate *end = [NSDate date];
    	//NSLog(@"%f",[end timeIntervalSincedate:begin]);
    	CFAbsoluteTime end = CFAbsoluteTimeGetCurrent();
    	NSLog(@"%f",end - begin);
    	
    	//2.将二进制转换为图片
    	UIImage *image = [UIImage imageWithData:data];
    	//3.显示图片
    	self.imageView.image = image;
    	*/
    	
    	//开启一个子线程,下载图片
    	[self performSelectorInBackground:@selector(download) withObject:nil];
    }
    
    • 在主线程中下载图片会影响性能,应该开启一个子线程
    - (void)download
    {
    	//1.下载图片
    	NSURL *url = [NSURL URLWihtString:@"图片资源网址"];
    	NSData *data = [NSData dataWithContentsOfURL:url];//耗时,应开启子线程
    	
    	//2.将二进制转换为图片
    	UIImage *image = [UIImage imageWithData:data];
    	
    	//3.更新UI
    #warning 注意:千万不要再子线程中更新UI,会出问题
    	//self.imageView.image = image;//不能子子线程中更新UI
    	//在主线程中更新UI
    	[self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];//开发中常用
    	
    	//[self performSelectorOnMainThread:@selector(updateImage:) withObject:image waitUntilDone:YES];
    	
    	NSLog(@"------");
    }
    
    - (void)updateImage:(UIImage *)image
    {
    	NSLog(@"++++++++");
    	self.imageView.image = image;
    }
    
    • waitUntilDone:
      • 如果传入YES,那么会等待@selector中的函数执行完毕,就可以执行之后的代码
      • 如果传入NO,那么不会等待@selector中的函数执行完毕,就可以执行之后的代码
    更新UI的方法
    • 1.使用setImage:(开发中常用)
     [self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
    
    • 2.使用自定义函数:(了解)
     [self performSelectorOnMainThread:@selector(updateImage:) withObject:image waitUntilDone:YES];
     
     - (void)updateImage:(UIImage *)image
    {
    	self.imageView.image = image;
    }
    
    • 3.使用:performSelector:(了解)
      • 可以在指定的线程中,调用指定对象的指定方法
     [self performSelector:@selector(updateImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
     
    - (void)updateImage:(UIImage *)image
    {
    	self.imageView.image = image;
    }
    
  • 相关阅读:
    鼠标的移动触发函数改变字体颜色
    Godaddy创始人:成就亿万富翁的10条规则
    关于编程,大学没有传授的十件事
    Using XAMPP for Local WordPress Theme Development
    100+ Resources for Web Developer
    你必须非常努力,才能看起来毫不费力
    建立WordPress博客网站——个人教程
    函数指针和指针函数
    每天写出好代码的5个建议
    LumiSoft Mail Server
  • 原文地址:https://www.cnblogs.com/KrystalNa/p/4780316.html
Copyright © 2011-2022 走看看