更新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