NSOperation/NSOperationQueue面向對象的線程技術。多線程
1 //建立線程隊列 2 NSOperationQueue *queue = [[NSOperationQueue alloc]init]; 3 4 //關閉暫停隊列,用於讓全部的線程加入隊列後在執行任務 5 [queue setSuspended:YES]; 6 7 //設置最大併發數, 8 queue.maxConcurrentOperationCount = 2; 9 10 //建立線程 11 NSInvocationOperation *operation1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(operation1:) object:@"operation1"]; 12 13 //設置線程優先級 14 operation1.queuePriority = NSOperationQueuePriorityNormal; 15 16 //建立第二個線程 17 NSInvocationOperation *operation2 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(operation2:) object:@"operation2"]; 18 //設置線程優先級 19 operation2.queuePriority = NSOperationQueuePriorityVeryHigh; 20 21 //將線程加入隊列 22 [queue addOperation:operation1]; 23 [queue addOperation:operation2]; 24 25 26 //用Block建立多線程 27 28 [queue addOperationWithBlock:^{ 29 30 //注意這裏咱們要將任務放進自動釋放池,由於這段代碼不在(主線程)中 31 @autoreleasepool { 32 33 for (int i = 0; i < 10; i ++) { 34 35 NSLog(@"operation3%d",i); 36 } 37 } 38 }]; 39 40 41 //開始隊列 42 [queue setSuspended:NO];
#import "UIImageView+cache.h" @implementation UIImageView (cache) - (void)setImages:(NSString *)str { //建立隊列 NSOperationQueue *queue = [[NSOperationQueue alloc]init]; //設置最大併發 queue.maxConcurrentOperationCount = 1; //建立線程 NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(operationAction:) object:str]; //將線程加入線程隊列 [queue addOperation:operation]; } - (void)operationAction:(NSString *)str { NSURL *url = [NSURL URLWithString:str]; NSData *data = [NSData dataWithContentsOfURL:url]; //在這裏咱們要修改UI了因此要從新回到主線程 //第一種回主線程的方式 [self performSelectorOnMainThread:@selector(setImage:) withObject:[UIImage imageWithData:data] waitUntilDone:YES]; /* //第二種方式回到主線程 [[NSOperationQueue mainQueue] addOperationWithBlock:^{ self.image = [UIImage imageWithData:data]; }]; */ } @end viewController中的代碼: #import "ViewController.h" #import "UIImageView+cache.h" @interface ViewController () @property (nonatomic, strong)NSMutableArray *dataArr; @end @implementation ViewController - (NSMutableArray *)dataArr { if (_dataArr == nil) { _dataArr = [NSMutableArray array]; return _dataArr; } return _dataArr; } - (void)viewDidLoad { [super viewDidLoad]; for (int i = 0; i < 8; i ++) { for (int j = 0; j < 6; j ++) { UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(j * 64, i * 80, 60, 75)]; imageview.backgroundColor = [UIColor yellowColor]; [self.view addSubview:imageview]; [self.dataArr addObject:imageview]; } } } - (IBAction)click:(UIButton *)sender { for (UIImageView *imageview in self.dataArr) { [imageview setImages:@"http://img31.mtime.cn/pi/2013/03/08/144644.81111130_1280X720.jpg"]; } } @end 這樣就解決了主線程阻塞的問題。