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;
    }
    
  • 相关阅读:
    加密算法
    git 误操作
    element项目发布
    node命令
    计划
    第一次碰见类似留几手的段子手
    【vue】---猫眼项目中使用js组件的时候-------loading 加载 无法移除的原因---------
    【异步】---异步解决方案---
    【问题-方法】---buffer---解决方法,butter 文件转字符串
    【大脑】--如何让大脑快速记忆
  • 原文地址:https://www.cnblogs.com/KrystalNa/p/4780316.html
Copyright © 2011-2022 走看看