叹落花 / 网络与多线程 / IOS多线程

0 0

   

IOS多线程

2015-05-04  叹落花

更新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
复制代码

 

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。如发现有害或侵权内容,请点击这里 或 拨打24小时举报电话:4000070609 与我们联系。

    0条评论

    发表

    请遵守用户 评论公约

    类似文章
    喜欢该文的人也喜欢 更多

    ×
    ×