IOS多線程 – 使用線程載入一張圖片 – NSThread(1)

來源:互聯網
上載者:User

更新UI的操作在IOS中其實和在Android中是一致的,都是不能在主線程中執行比較耗時的操作,所以需要開啟新線程去做這些操作,以免阻塞主線程,當新線程中的操作完成之後,調用主線程來更新UI。下面就是一個這樣的例子:

1、聲明ImageView控制項

1 #import <UIKit/UIKit.h>2 3 @interface DemoDispatchQueueViewController : UIViewController4 @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 *)nibBundleOrNil10 {11     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];12     if (self) {13     }14     return self;15 }16 17 - (void)viewDidLoad18 {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 *) imageUrl34 {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)didReceiveMemoryWarning51 {52     [super didReceiveMemoryWarning];53     // Dispose of any resources that can be recreated.54 }55 56 @end

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.