iOS開發中實作多線程有三種方式:NSThread,NSOperation和GCD。本文介紹三種方式的具體實作。
1.NSThread
初始化一個線程有兩種方式:
/*******NSObject的類方法**************/
[self performSelectorInBackground:@selector(secondMethod) withObject:self];
/*******NSThread,有兩種方法**********/
//1.類方法 會自動運作main方法
[NSThread detachNewThreadSelector:@selector(firstMethod) toTarget:self withObject:nil];
//2.alloc 線程需要start
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(firstMethod) object:nil];
[thread start];
2.NSOperation
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
queue.maxConcurrentOperationCount = 3;//最多同時運作的線程數
for (int i=0; i<10; i++) {
MyOperation *opr = [[MyOperation alloc] init];//自定義一個operation類,繼承自NSOperation
opr.time = i;
[queue addOperation:opr];
[opr release];
}
MyOperation.h
#import <Foundation/Foundation.h>
@interface MyOperation : NSOperation
@property (nonatomic, assign) int time;
@end
MyOperation.m
#import "MyOperation.h"
@implementation MyOperation
@synthesize time;
//隻要執行個體化該對象并添加到隊列中之後,會自動調用main方法
- (void)main
{
sleep(self.time);
NSLog(@"%d", self.time);
}
@end
3. GCD
關于GCD會用另一篇文章介紹,此處直接寫用法
//建立一個串行線程隊列,第一個參數是隊列的名字,第二個參數不知道
dispatch_queue_t opqueue = dispatch_queue_create("my operation queue", NULL);
//異步執行線程,在t中執行block語句
dispatch_async(opqueue, ^{
[self first];
});
//得到一個并行線程隊列,第一個參數是優先級
dispatch_queue_t opqueue2 = dispatch_get_global_queue(0, 0);
dispatch_async(opqueue2, ^{
[self second];
});
另外,這些線程不能操作UI,但是可以回調,讓來執行UI方面的操作,有兩種方式:
//回到主線程
//第一種方法
// [self performSelectorOnMainThread:@selector(first) withObject:self waitUntilDone:NO];
//第二種方法
dispatch_async(dispatch_get_main_queue(), ^{
_imageView.image = img;
});