在iOS中, 界面刷新在主线程中进行, 这导致NSURLSession远程下载图片使用UIImageView直接设置Image并不能及时刷新界面.

下面的代码演示了如何使用 performSelectorOnMainThread: withObject:  waitUntilDone: 方法来及时刷新图片

1. 创建iOS空应用程序(Empty Application).

2. 加入一个控制器类. 在YYAppDelegate.m中修改

#import "MainViewController.h"

@implementation YYAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor]; self.window.rootViewController = [[MainViewController alloc] initWithNibName:nil bundle:nil]; [self.window makeKeyAndVisible];
return YES;
}

3. 修改MainViewController.m文件

 //
// MainViewController.m
// UIByCodeDemo0602_ImageView
//
// Created by yao_yu on 14-6-3.
// Copyright (c) 2014年 yao_yu. All rights reserved.
// #import "MainViewController.h" @interface MainViewController () @property(nonatomic, strong)UILabel *header;
@property(nonatomic, strong)UIImageView *imageView;
@property(nonatomic, strong)UIImage *imagedata; @end @implementation MainViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
} - (void)viewDidLoad
{
[super viewDidLoad];
self.imagedata = nil; //创建标题标签
self.header = [[UILabel alloc] init];
self.header.text = @"示意图";
self.header.textAlignment = NSTextAlignmentCenter;
[self.view addSubview: self.header];
[self.header setTranslatesAutoresizingMaskIntoConstraints: NO]; //创建图片视图
self.imageView = [[UIImageView alloc] init];
[self.imageView setBackgroundColor: [UIColor blueColor]];
[self.imageView setImage: [UIImage imageWithContentsOfFile:@"/Users/yao_yu/Documents/aaa/3002302_.png"]];
self.imageView.layer.cornerRadius = ;
[self.view addSubview:self.imageView];
[self.imageView setTranslatesAutoresizingMaskIntoConstraints: NO]; //创建前一张按钮
UIButton *prevButton = [[UIButton alloc] init];
prevButton.frame = CGRectMake(, , , );
[prevButton setBackgroundColor:[UIColor redColor]];
[prevButton setTitle:@"前一张" forState:UIControlStateNormal];
[prevButton addTarget:self action:@selector(onShowPrevImage:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview: prevButton];
[prevButton setTranslatesAutoresizingMaskIntoConstraints: NO]; //创建后一张按钮
UIButton *nextButton = [[UIButton alloc] init];
nextButton.frame = CGRectMake(, , , );
[nextButton setBackgroundColor:[UIColor redColor]];
[nextButton setTitle:@"后一张" forState:UIControlStateNormal];
[nextButton addTarget:self action:@selector(onShowNextImage:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview: nextButton];
[nextButton setTranslatesAutoresizingMaskIntoConstraints: NO]; //约束
NSMutableArray *contraits = [NSMutableArray array];
NSDictionary *metrics = [NSDictionary dictionaryWithObjectsAndKeys:@, @"VDist", @, @"Padding", nil];
UILabel *header = self.header;
UIImageView *imageView = self.imageView;
NSDictionary *views = NSDictionaryOfVariableBindings(header, imageView, prevButton, nextButton); [contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-Padding-[header]-Padding-|" options: metrics:metrics views:views]];
[contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-Padding-[prevButton]-(>=0)-[nextButton(==prevButton)]-Padding-|" options: metrics:metrics views:views]]; [contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-Padding-[imageView]-Padding-|" options: metrics:metrics views:views]];
[contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-VDist-[header]-Padding-[imageView]-(>=VDist)-|" options: metrics:metrics views:views]];
//垂直居中
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:prevButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier: constant:]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:nextButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier: constant:]]; [self.view addConstraints:contraits]; } - (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
} -(void)onShowPrevImage:(id)sender
{
NSURL *URL = [NSURL URLWithString:@"http://img.gtimg.cn/images/hq_parts/hushen/stocks/300230.png"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
self.imageView.image = nil;
self.imagedata = [UIImage imageWithData:data];
[self performSelectorOnMainThread:@selector(updateMyImage) withObject:nil waitUntilDone:NO];
}]; [task resume]; } -(void)onShowNextImage:(id)sender
{
NSURL *URL = [NSURL URLWithString:@"http://img.gtimg.cn/images/hq_parts/hushen/stocks/300023.png"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
self.imageView.image = nil;
self.imagedata = [UIImage imageWithData:data];
[self performSelectorOnMainThread:@selector(updateMyImage) withObject:nil waitUntilDone:NO];
}]; [task resume];
} - (void)updateMyImage
{
if (!self.imageView.image)
self.imageView.image = self.imagedata;
return;
} @end

4. 运行

iOS: 学习笔记, 使用performSelectorOnMainThread及时刷新UIImageView的更多相关文章

  1. iOS学习笔记-精华整理

    iOS学习笔记总结整理 一.内存管理情况 1- autorelease,当用户的代码在持续运行时,自动释放池是不会被销毁的,这段时间内用户可以安全地使用自动释放的对象.当用户的代码运行告一段 落,开始 ...

  2. iOS学习笔记总结整理

    来源:http://mobile.51cto.com/iphone-386851_all.htm 学习IOS开发这对于一个初学者来说,是一件非常挠头的事情.其实学习IOS开发无外乎平时的积累与总结.下 ...

  3. [置顶] iOS学习笔记47——图片异步加载之EGOImageLoading

    上次在<iOS学习笔记46——图片异步加载之SDWebImage>中介绍过一个开源的图片异步加载库,今天来介绍另外一个功能类似的EGOImageLoading,看名字知道,之前的一篇学习笔 ...

  4. IOS学习笔记48--一些常见的IOS知识点+面试题

      IOS学习笔记48--一些常见的IOS知识点+面试题   1.堆和栈什么区别? 答:管理方式:对于栈来讲,是由编译器自动管理,无需我们手工控制:对于堆来说,释放工作由程序员控制,容易产生memor ...

  5. iOS学习笔记之UITableViewController&UITableView

    iOS学习笔记之UITableViewController&UITableView 写在前面 上个月末到现在一直都在忙实验室的事情,与导师讨论之后,发现目前在实验室完成的工作还不足以写成毕业论 ...

  6. iOS学习笔记31-从图册获取图片和视频

    一.从图册中获取本地图片和视频 从图册中获取文件,我们使用的是UIImagePickerController,这个类我们在之前的摄像头中使用过,这里是链接:iOS学习笔记27-摄像头,这里我们使用的是 ...

  7. iOS学习笔记20-地图(二)MapKit框架

    一.地图开发介绍 从iOS6.0开始地图数据不再由谷歌驱动,而是改用自家地图,当然在国内它的数据是由高德地图提供的. 在iOS中进行地图开发主要有三种方式: 利用MapKit框架进行地图开发,利用这种 ...

  8. iOS学习笔记——AutoLayout的约束

    iOS学习笔记——AutoLayout约束 之前在开发iOS app时一直以为苹果的布局是绝对布局,在IB中拖拉控件运行或者直接使用代码去调整控件都会发上一些不尽人意的结果,后来发现iOS在引入了Au ...

  9. IOS学习笔记25—HTTP操作之ASIHTTPRequest

    IOS学习笔记25—HTTP操作之ASIHTTPRequest 分类: iOS2012-08-12 10:04 7734人阅读 评论(3) 收藏 举报 iosios5网络wrapper框架新浪微博 A ...

随机推荐

  1. mongodb基本操作及存储图片显示方案

    先介绍下mongodb的基本操作及使用 第一部:开启安全性验证 如果需要给MongoDB数据库使用安全验证,则需要用--auth开启安全性检查,则只有数据库认证的用户才能执行读写操作,开户安全性检查, ...

  2. Ajax交互demo1

    一.概念 Ajax异步请求刷新. 浏览器在用户不知道的情况下,偷偷地跟服务器交互,然后返回数据给浏览器显示. 异步过程:当HTTP请求发送后,通过Ajax技术使用的XMLHttpRequest对象来发 ...

  3. gwt中java与js的相互调用

    1. java通过jsni调用内部js Button button = new Button("java调用内部jsni的js方法"); button.addClickHandle ...

  4. asp.net采用OLEDB方式导入Excel数据时提示:未在本地计算机上注册"Microsoft.Jet.OLEDB.4.0" 提供程序"

    笔者在项目中做做了一个从Excel表格中导入数据的模块.大体上asp.net项目中导入Excel大体分成三类: 1)采用c#内置方案System.Data.OleDb(限制较小, 通用) 2)采用Ex ...

  5. c#常用工具类:文件和二进制转换

    //================二进制相关转换类============== #region 将文件转换为二进制数组 /// <summary> /// 将文件转换为二进制数组 /// ...

  6. 修改Tomcat 6 默认的ROOT

    1.找到conf/server.xml. 2.找到Host节点. 3.在该节点中添加子节点<Context path="" docBase="项目名称" ...

  7. [Webpack 2] Maintain sane file sizes with webpack code splitting

    As a Single Page Application grows in size, the size of the payload can become a real problem for pe ...

  8. java Thread.join()

    thread1.join()方法阻塞调用此方法的线程,直到线程thread1完成,此线程再继续. 通常用于在main()主线程内,等待其它线程完成再结束main()主线程 @Test /** * ou ...

  9. ubuntu15.10下sublime text3 无法输入中文解决办法

    原文链接:http://geek.csdn.net/news/detail/44464 1.首先保证你的电脑有c++编译环境 如果没有,通过以下指令安装 sudo apt-get install bu ...

  10. tomcat中jsp编译

    tomcat运行的工程中,jsp替换文件后可能不起作用.原因是jsp也是需要编译的.编译后的文件存放在tomcat/work文件夹下.如果替换不起作用,可以将work文件夹下的内容删除掉,重新启tom ...