zoukankan      html  css  js  c++  java
  • IOS多线程 使用线程加载一张图片 NSThread(1)

    更新UI的操作在IOS中其实和在Android中是一致的,都是不能在主线程中执行比较耗时的操作,所以需要开启新线程去做这些操作,以免阻塞主线程,当新线程中的操作完成之后,调用主线程来更新UI。下面就是一个这样的例子:

    1、声明ImageView控件

    1 #import <UIKit/UIKit.h>
    2 
    3 @interface DemoDispatchQueueViewController : UIViewController
    4 @property(nonatomic,strong) UIImageView *imageView;
    5 @end

    2、完成功能

     1 #import "DemoDispatchQueueViewController.h"
     2 
     3 @interface DemoDispatchQueueViewController ()
     4 
     5 @end
     6 
     7 @implementation DemoDispatchQueueViewController
     8 @synthesize imageView;
     9 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    10 {
    11     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    12     if (self) {
    13     }
    14     return self;
    15 }
    16 
    17 - (void)viewDidLoad
    18 {
    19     [super viewDidLoad];
    20     // Do any additional setup after loading the view.
    21     self.title = @"GCD Demo";
    22     
    23     self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 300, 380)];
    24     
    25     self.imageView.contentMode = UIViewContentModeScaleToFill;
    26     
    27     [self.view addSubview:imageView];
    28     
    29     [NSThread detachNewThreadSelector:@selector(loadImageByUrl:) toTarget:self withObject:@"http://image.rayliimg.cn/0008/2009-01-15/images/2009115135825184.jpg"];
    30     
    31 }
    32 
    33 -(void) loadImageByUrl:(NSString *) imageUrl
    34 {
    35     NSLog(@"url is :%@",imageUrl);
    36     NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
    37     UIImage *image = [UIImage imageWithData:data];
    38     
    39     if(image != nil){
    40         [self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
    41     }else{
    42         NSLog(@"无法载入相应的图片");
    43     }
    44 }
    45 -(void) setImage:(UIImage*) image{
    46     [self.imageView setImage:image];
    47 }
    48 
    49 
    50 - (void)didReceiveMemoryWarning
    51 {
    52     [super didReceiveMemoryWarning];
    53     // Dispose of any resources that can be recreated.
    54 }
    55 
    56 @end
  • 相关阅读:
    python接口自动化(三)--如何设计接口测试用例(详解)
    python接口自动化(二)--什么是接口测试、为什么要做接口测试(详解)
    python接口自动化(一)--什么是接口、接口优势、类型(详解)
    PostgreSQL建立分区表示例
    PostgreSQL中的时间操作总结
    linux系统命令:yum和apt-get
    oracle中的连接查询与合并查询总结
    oracle中时间运算
    oracle中一些用法总结
    oracle中substr与instr
  • 原文地址:https://www.cnblogs.com/xinye/p/2991190.html
Copyright © 2011-2022 走看看