您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 多執行緒:NSThread 與 NSInvocationOperation

編輯:iOS 相關資訊

目前多執行緒大多使用 GCD,但了解其他方式仍有其價值。本文示範 NSThread 與 NSInvocationOperation 的簡單用法,以背景下載多張圖片並播放動畫為例。

先在類別擴展中宣告 image view 與操作佇列:

@interface yxpViewController ()
{
    UIImageView *_imageView;
    // 宣告一個佇列
    NSOperationQueue *_operationQueue;
}
@end

在 viewDidLoad 中初始化佇列並限定同時只運行一個執行緒:

- (void)viewDidLoad
{
    [super viewDidLoad];
    _operationQueue = [[NSOperationQueue alloc] init];
    [_operationQueue setMaxConcurrentOperationCount:1];
    _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 70, 300, 450)];
    [self.view addSubview:_imageView];
    // 方法一:建立 NSInvocationOperation 並加入佇列
    NSInvocationOperation *theOp = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(addTaskMethod:) object:_imageView];
    [_operationQueue addOperation:theOp];
    // 方法二(等效):
    // [NSThread detachNewThreadSelector:@selector(addTaskMethod:) toTarget:self withObject:nil];
}

注意:直接呼叫 theOp 的 start 是同步的,還會等背景執行緒完成;把它加入佇列才是與主執行緒同時執行的異步行為。

背景執行緒中下載圖片的方法:

- (void)addTaskMethod:(id)data
{
    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;
    // 回到主執行緒更新 UI(背景執行緒不能直接操作 UI)
    [self performSelectorOnMainThread:@selector(startImageViewAnimating) withObject:nil waitUntilDone:YES];
}

下載圖片的方法:

-(UIImage *) getImageFromURL:(NSString *)fileURL {
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
    return [UIImage imageWithData:data];
}

重點觀念:非主執行緒不能直接操作 UI,必須用 performSelectorOnMainThread 回到主執行緒播放動畫。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved