今天多數專案都直接用 GCD 解決併發問題,但 NSOperation 系列還是有它的價值:可以設定最大併發數、可以取消、可以掛相依關係。搭配最原始的 NSThread 一起理解,你會更清楚 iOS 上「開一條執行緒」到底發生了什麼事。
下面用同一個需求示範:在背景執行緒下載五張圖片,組合成動畫後回到主執行緒播放。
@interface yxpViewController ()
{
UIImageView *_imageView;
// 宣告一個佇列
NSOperationQueue *_operationQueue;
}
@end
@implementation yxpViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// 初始化操作佇列
_operationQueue = [[NSOperationQueue alloc] init];
// 限定該佇列同時只跑一條執行緒
[_operationQueue setMaxConcurrentOperationCount:1];
// 初始化 ImageView
_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 70, 300, 450)];
_imageView.backgroundColor = [UIColor grayColor];
_imageView.animationDuration = 3.0;
_imageView.animationRepeatCount = 0;
[self.view addSubview:_imageView];
}
@end
建立一個 NSInvocationOperation 物件並指定要跑的 method。selector 後面是丟到另一條執行緒執行的方法,object 後面是要傳給該方法的參數。
NSInvocationOperation *theOp = [[NSInvocationOperation alloc]
initWithTarget:self
selector:@selector(addTaskMethod:)
object:_imageView];
// 也可以直接呼叫 start,但那是同步的:主執行緒會等背景工作跑完才往下走
// [theOp start];
// 加入佇列才是非同步,theOp 與主執行緒同時進行,這才是我們要的效果
[_operationQueue addOperation:theOp];
效果等同上面那一段,只是把「開一條新執行緒」這件事講得更直白:
[NSThread detachNewThreadSelector:@selector(addTaskMethod:)
toTarget:self
withObject:nil];
// 在另一條執行緒上執行的方法
- (void)addTaskMethod:(id)data
{
NSString *url1 = @"https://h.hiphotos.baidu.com/image/w%3D230/sign=b2d5c289123853438ccf8022a311b01f/91ef76c6a7efce1b1ae9f92fad51f3deb58f6510.jpg";
NSString *url2 = @"https://h.hiphotos.baidu.com/image/pic/item/d058ccbf6c81800aae834e8bb33533fa838b47d5.jpg";
NSString *url3 = @"https://d.hiphotos.baidu.com/image/pic/item/f2deb48f8c5494eec3ba65132ff5e0fe99257e1b.jpg";
NSString *url4 = @"https://g.hiphotos.baidu.com/image/pic/item/a6efce1b9d16fdfa81f4ace4b68f8c5494ee7b1b.jpg";
NSString *url5 = @"https://g.hiphotos.baidu.com/image/pic/item/d6ca7bcb0a46f21f70031fdbf4246b600c33ae07.jpg";
NSArray *array = [[NSArray alloc] initWithObjects:url1, url2, url3, url4, url5, nil];
NSMutableArray *imageArray = [[NSMutableArray alloc] initWithCapacity:20];
for (NSString *string in array) {
UIImage *image = [self getImageFromURL:string];
[imageArray addObject:image];
}
_imageView.animationImages = imageArray;
// 回到主執行緒播放動畫
[self performSelectorOnMainThread:@selector(startImageViewAnimating)
withObject:nil
waitUntilDone:YES];
}
- (void)startImageViewAnimating
{
[_imageView startAnimating];
}
// 下載圖片
- (UIImage *)getImageFromURL:(NSString *)fileURL
{
NSLog(@"執行圖片下載函數");
UIImage *result;
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
result = [UIImage imageWithData:data];
return result;
}
UIKit 不是執行緒安全的,所有跟畫面有關的操作都必須回到主執行緒。上面用 performSelectorOnMainThread:withObject:waitUntilDone: 就是這個用意;你可以故意在非主執行緒直接呼叫 startAnimating,行為會變得很難預測。另外這個方法只接受一個參數物件,要傳多個值就打包成陣列或字典。
最後提醒,範例裡的 dataWithContentsOfURL: 是同步下載,認真做的時候應該換成 NSURLSession,並且加上錯誤處理與快取。