在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. mvn开发可执行的java程序

    1.  用maven-assembly-plugin插件 2. 在项目的pom文件中加入以下该插件的配置 <span style="font-size:18px;">& ...

  2. Day 3 @ RSA Conference Asia Pacific & Japan 2016 (morning)

    09.00 – 09.45 hrs Tracks Cloud, Mobile, & IoT Security    A New Security Paradigm for IoT (Inter ...

  3. Mysql Binlog 三种格式介绍及分析

    一.Mysql Binlog格式介绍       Mysql binlog日志有三种格式,分别为Statement,MiXED,以及ROW! 1.Statement:每一条会修改数据的sql都会记录在 ...

  4. Uncaught TypeError: Cannot read property 'post' of undefined

  5. android80 HttpClient框架提交数据 get方式

    package com.itheima.httpclient; import java.io.IOException; import java.io.InputStream; import java. ...

  6. java程序员从笨鸟到菜鸟系列

    http://blog.csdn.net/csh624366188/article/category/888600

  7. BTrace使用总结

    btracejvisualvmhotswap  一.背景        在生产环境中可能经常遇到各种问题,定位问题需要获取程序运行时的数据信息,如方法参数.返回值.全局变量.堆栈信息等.为了获取这些数 ...

  8. git操作github

    转自http://www.cnblogs.com/fnng/archive/2012/01/07/2315685.html 怕找不到~ 本文在我之前的那篇<git/github学习笔记>的 ...

  9. 30种mysql优化sql语句查询的方法<转>

    转自百度文库 1.对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引.   2.应尽量避免在 where 子句中使用!=或<>操作符,否 ...

  10. step2 uboot tag存储主要部分代码

      cmd_bootm.c //传递给内核的参数      int do_bootm (cmd_tbl_t *cmdtp, int flag, int argc, char *argv[])     ...