- 線程之間的通信基本概念: 在一個進程中,線程往往不是孤立存在的,多個線程之間經常需要進行通信;
- 線程之間通信的體現: 一個線程傳遞數據給另一個線程; 在一個線程中執行完任務之后轉到另一個線程繼續執行任務;
- 線程之間通信的常用的方法:
1)NSThread方法:
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;
2)gcd方法
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
// 1.下載圖片(耗時)
dispatch_async(queue, ^{
//分線程中執行好事操作
dispatch_sync(dispatch_get_main_queue(), ^{
主線程中更新ui
});
});
3)NSOperation
方法1:
// 1.創建一個新的隊列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// 2.添加任務(操作)
[queue addOperationWithBlock:^{
// 2.1在子線程中下載圖片
NSURL *url = [NSURL URLWithString:@"http://imgcache.mysodao.com/img2/M04/8C/74/CgAPDk9dyjvS1AanAAJPpRypnFA573_700x0x1.JPG"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
// 2.2回到主線程更新UI
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.imageView.image = image;
}];
}];
方法2:(添加依賴庫)
/ 1.創建一個隊列
// 一般情況下, 在做企業開發時候, 都會定義一個全局的自定義隊列, 便于使用
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// 2.添加一個操作下載第一張圖片
__block UIImage *image1 = nil;
NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
NSURL *url = [NSURL URLWithString:@"http://imgcache.mysodao.com/img2/M04/8C/74/CgAPDk9dyjvS1AanAAJPpRypnFA573_700x0x1.JPG"];
NSData *data = [NSData dataWithContentsOfURL:url];
image1 = [UIImage imageWithData:data];
}];
// 3.添加一個操作下載第二張圖片
__block UIImage *image2 = nil;
NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
NSURL *url = [NSURL URLWithString:@"http://imgcache.mysodao.com/img1/M02/EE/B5/CgAPDE-kEtqjE8CWAAg9m-Zz4qo025-22365300.JPG"];
NSData *data = [NSData dataWithContentsOfURL:url];
image2 = [UIImage imageWithData:data];
}];
// 4.添加一個操作合成圖片
NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
UIGraphicsBeginImageContext(CGSizeMake(200, 200));
[image1 drawInRect:CGRectMake(0, 0, 100, 200)];
[image2 drawInRect:CGRectMake(100, 0, 100, 200)];
UIImage *res = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// 5.回到主線程更新UI
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.imageView.image = res;
}];
}];
// 6.添加依賴
[op3 addDependency:op1];
[op3 addDependency:op2];
// 7.添加操作到隊列中
[queue addOperation:op1];
[queue addOperation:op2];
[queue addOperation:op3];