標籤:好的 image cut 對象 定義 current nil ati 具體步驟
概述
NSOperation是基於GCD的封裝更加物件導向,在使用上也是有任務跟隊列的概念,分別對應兩個類NSOperation 、NSOperationQueue
NSOperation和NSOperationQueue實現多線程的具體步驟
- 現將需要執行的操作封裝到一個NSOperation對象中。
- 然後將NSOperation對象添加到NSOperationQueue中
- 系統會自動將NSOperationQueue中的NSOperation取出來
- 將取出的NSOperation封裝的操作放到一條線程中執行
NSOperation
NSOperation是一個抽象類別,使用時候需要使用其子類。NSOperation總共有兩個子類。
- NSInvocationOperation
- NSBlockOperation
開發中一般NSOperation子類通常與NSOperationQueue一起使用才能更好的開闢線程。
NSOperationQueue
NSOperation可以調用start方法類執行任務,但預設是同步的。如果將NSOperation添加到NSOperationQueue中執行,系統會自動非同步執行NSOperation中的操作。
NSOperationQueue只用兩種類型,分別是主隊列跟非主隊列(包含串列、並發)。兩種隊列的擷取方式:
[NSOperationQueue mainQueue]; // 主隊類[[NSOperationQueue alloc] init]; // 非主隊列
凡是添加到主隊列的任務都是在主線程中執行。非主隊列的任務會自動添加到子線程中執行。並發跟串列通過隊列的maxConcurrentOperationCount決定。
#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(task) object:nil]; [queue addOperation:operation];// [operation start]; NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"------------%@", [NSThread currentThread]); }]; // 添加額外的任務才會在子線程執行 [blockOperation addExecutionBlock:^{ NSLog(@"------------%@", [NSThread currentThread]); }]; [queue addOperation:blockOperation]; // [blockOperation start]; }- (void)task{ NSLog(@"------------%@", [NSThread currentThread]);}
一旦NSOperation添加進NSOperationQueue,無須調用NSOperation的start方法,內部自動回調用NSOperation的start。
開發中還可以自訂NSOperation的方式,重寫main方法將任務封裝進來。如果任務的代碼比較多,在很多程式的很多地方都需要使用,建議採用這種方式。
#import "FMOperation.h"@implementation FMOperation- (void)main{ // 封裝任務 }@end
iOS開發系列-NSOperation