首页 > 代码库 > iOS: 学习笔记, 使用performSelectorOnMainThread及时刷新UIImageView

iOS: 学习笔记, 使用performSelectorOnMainThread及时刷新UIImageView

在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文件

  1 //
  2 //  MainViewController.m
  3 //  UIByCodeDemo0602_ImageView
  4 //
  5 //  Created by yao_yu on 14-6-3.
  6 //  Copyright (c) 2014年 yao_yu. All rights reserved.
  7 //
  8 
  9 #import "MainViewController.h"
 10 
 11 @interface MainViewController ()
 12 
 13 @property(nonatomic, strong)UILabel *header;
 14 @property(nonatomic, strong)UIImageView *imageView;
 15 @property(nonatomic, strong)UIImage *imagedata;
 16 
 17 @end
 18 
 19 @implementation MainViewController
 20 
 21 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
 22 {
 23     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
 24     if (self) {
 25         // Custom initialization
 26     }
 27     return self;
 28 }
 29 
 30 - (void)viewDidLoad
 31 {
 32     [super viewDidLoad];
 33     self.imagedata =http://www.mamicode.com/ nil;
 34     
 35     //创建标题标签
 36     self.header = [[UILabel alloc] init];
 37     self.header.text = @"示意图";
 38     self.header.textAlignment = NSTextAlignmentCenter;
 39     [self.view addSubview: self.header];
 40     [self.header setTranslatesAutoresizingMaskIntoConstraints: NO];
 41     
 42     //创建图片视图
 43     self.imageView = [[UIImageView alloc] init];
 44     [self.imageView setBackgroundColor: [UIColor blueColor]];
 45     [self.imageView setImage: [UIImage imageWithContentsOfFile:@"/Users/yao_yu/Documents/aaa/3002302_.png"]];
 46     self.imageView.layer.cornerRadius = 10;
 47     [self.view addSubview:self.imageView];
 48     [self.imageView setTranslatesAutoresizingMaskIntoConstraints: NO];
 49     
 50     //创建前一张按钮
 51     UIButton *prevButton = [[UIButton alloc] init];
 52     prevButton.frame = CGRectMake(0, 20, 300, 20);
 53     [prevButton setBackgroundColor:[UIColor redColor]];
 54     [prevButton setTitle:@"前一张" forState:UIControlStateNormal];
 55     [prevButton addTarget:self action:@selector(onShowPrevImage:) forControlEvents:UIControlEventTouchUpInside];
 56     [self.view addSubview: prevButton];
 57     [prevButton setTranslatesAutoresizingMaskIntoConstraints: NO];
 58     
 59     //创建后一张按钮
 60     UIButton *nextButton = [[UIButton alloc] init];
 61     nextButton.frame = CGRectMake(0, 20, 300, 20);
 62     [nextButton setBackgroundColor:[UIColor redColor]];
 63     [nextButton setTitle:@"后一张" forState:UIControlStateNormal];
 64     [nextButton addTarget:self action:@selector(onShowNextImage:) forControlEvents:UIControlEventTouchUpInside];
 65     [self.view addSubview: nextButton];
 66     [nextButton setTranslatesAutoresizingMaskIntoConstraints: NO];
 67     
 68     //约束
 69     NSMutableArray *contraits = [NSMutableArray array];
 70     NSDictionary *metrics = [NSDictionary dictionaryWithObjectsAndKeys:@20, @"VDist", @5, @"Padding", nil];
 71     UILabel *header = self.header;
 72     UIImageView *imageView = self.imageView;
 73     NSDictionary *views = NSDictionaryOfVariableBindings(header, imageView, prevButton, nextButton);
 74     
 75     [contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-Padding-[header]-Padding-|" options:0 metrics:metrics views:views]];
 76     [contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-Padding-[prevButton]-(>=0)-[nextButton(==prevButton)]-Padding-|" options:0 metrics:metrics views:views]];
 77     
 78     [contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-Padding-[imageView]-Padding-|" options:0 metrics:metrics views:views]];
 79     [contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-VDist-[header]-Padding-[imageView]-(>=VDist)-|" options:0 metrics:metrics views:views]];
 80     //垂直居中
 81     [self.view addConstraint:[NSLayoutConstraint constraintWithItem:prevButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];
 82     [self.view addConstraint:[NSLayoutConstraint constraintWithItem:nextButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];
 83     
 84     [self.view addConstraints:contraits];
 85     
 86 }
 87 
 88 - (void)didReceiveMemoryWarning
 89 {
 90     [super didReceiveMemoryWarning];
 91 }
 92 
 93 -(void)onShowPrevImage:(id)sender
 94 {
 95     NSURL *URL = [NSURL URLWithString:@"http://img.gtimg.cn/images/hq_parts/hushen/stocks/300230.png"];
 96     NSURLRequest *request = [NSURLRequest requestWithURL:URL];
 97     NSURLSession *session = [NSURLSession sharedSession];
 98     NSURLSessionDataTask *task = [session dataTaskWithRequest:request
 99                                             completionHandler:
100                                   ^(NSData *data, NSURLResponse *response, NSError *error) {
101                                       self.imageView.image = nil;
102                                       self.imagedata =http://www.mamicode.com/ [UIImage imageWithData:data];
103                                       [self performSelectorOnMainThread:@selector(updateMyImage) withObject:nil  waitUntilDone:NO];
104                                   }];
105     
106     [task resume];
107     
108 }
109 
110 -(void)onShowNextImage:(id)sender
111 {
112     NSURL *URL = [NSURL URLWithString:@"http://img.gtimg.cn/images/hq_parts/hushen/stocks/300023.png"];
113     NSURLRequest *request = [NSURLRequest requestWithURL:URL];
114     NSURLSession *session = [NSURLSession sharedSession];
115     NSURLSessionDataTask *task = [session dataTaskWithRequest:request
116                                             completionHandler:
117                                   ^(NSData *data, NSURLResponse *response, NSError *error) {
118                                       self.imageView.image = nil;
119                                       self.imagedata =http://www.mamicode.com/ [UIImage imageWithData:data];
120                                       [self performSelectorOnMainThread:@selector(updateMyImage) withObject:nil  waitUntilDone:NO];
121                                   }];
122     
123     [task resume];
124 }
125 
126 - (void)updateMyImage
127 {
128     if (!self.imageView.image)
129         self.imageView.image = self.imagedata;
130     return;
131 }
132 
133 @end

4. 运行