iOS中performSelectorOnMainThread刷新图片

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

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

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

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

  1. #import "MainViewController.h"  
  2.   
  3. @implementation YYAppDelegate  
  4.   
  5. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
  6. {  
  7.     self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];  
  8.     // Override point for customization after application launch.  
  9.     self.window.backgroundColor = [UIColor whiteColor];  
  10.       
  11.     self.window.rootViewController = [[MainViewController alloc] initWithNibName:nil bundle:nil];  
  12.       
  13.     [self.window makeKeyAndVisible];  
  14.     return YES;  
  15. }  

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(nonatomicstrong)UILabel *header;  
  • @property(nonatomicstrong)UIImageView *imageView;  
  • @property(nonatomicstrong)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 addSubviewself.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 = 10;  
  •     [self.view addSubview:self.imageView];  
  •     [self.imageView setTranslatesAutoresizingMaskIntoConstraints: NO];  
  •       
  •     //创建前一张按钮  
  •     UIButton *prevButton = [[UIButton alloc] init];  
  •     prevButton.frame = CGRectMake(02030020);  
  •     [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(02030020);  
  •     [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:@20@"VDist"@5@"Padding", nil 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:0 metrics:metrics views:views]];  
  •     [contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-Padding-[prevButton]-(>=0)-[nextButton(==prevButton)]-Padding-|" options:0 metrics:metrics views:views]];  
  •       
  •     [contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-Padding-[imageView]-Padding-|" options:0 metrics:metrics views:views]];  
  •     [contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-VDist-[header]-Padding-[imageView]-(>=VDist)-|" options:0 metrics:metrics views:views]];  
  •     //垂直居中  
  •     [self.view addConstraint:[NSLayoutConstraint constraintWithItem:prevButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];  
  •     [self.view addConstraint:[NSLayoutConstraint constraintWithItem:nextButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];  
  •       
  •     [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  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值