NSOperation其實(shí)就是蘋果對GCD的封裝,把GCD封裝成面向?qū)ο蟮木幊?,讓開發(fā)者使用起來更加方便,簡潔。
NSOperation的核心
- NSOperation操作
- 不能直接使用。
- 定義子類共有的屬性和方法。
- 子類:
- NSInvocationOperation(Swift里面沒有)
- NSBlockOperation
- NSOperationQueue隊列
- 將"操作" 添加到 "隊列"類似于GCD將"任務(wù)"添加到 "隊列"。
- 隊列:本質(zhì)上 就是GCD的并發(fā)隊列。
- 操作:異步執(zhí)行任務(wù)。
//創(chuàng)建一個NSInvocationOperation NSInvocationOperation * op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(test:) object:@"invocation"]; //創(chuàng)建隊列 NSOperationQueue * q = [[NSOperationQueue alloc]init]; //將操作添加到隊列 - 會自動異步執(zhí)行調(diào)度方法 [q addOperation:op];//創(chuàng)建NSBlockOperation對象 NSBlockOperation * op = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"%@ --- %d",[NSThread currentThread],i); }]; //創(chuàng)建隊列 NSOperationQueue * q = [[NSOperationQueue alloc]init]; //添加到隊列 [q addOperation:op];
線程間的通訊(開發(fā)中常用寫法)
[self.opQueue addOperationWithBlock:^{
NSLog(@"耗時操作 %@",[NSThread currentThread]);
//主線程更新 UI
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
NSLog(@ %@",[NSThread currentThread]);
}];
}];
最大并發(fā)數(shù)
//這個屬性便能控制線程的最大并發(fā)數(shù)
self.opQueue.maxConcurrentOperationCount = 2;
隊列的暫停和繼續(xù)
- suspended: 決定隊列的暫停和繼續(xù)
//YES暫停NO繼續(xù) self.opQueue.suspended = NO; - operationCount : 隊列中的操作數(shù)
self.opQueue.operationCount
取消所有操作
- 隊列掛起的時候,不會清空內(nèi)部的操作.只有在隊列繼續(xù)的時候才會清空。
- 正在執(zhí)行的操作也不會被取消。
[self.opQueue cancelAllOperations];
依賴關(guān)系
例子:
//1.下載
NSBlockOperation * op1 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"下載---%@",[NSThread currentThread]);
[NSThread sleepForTimeInterval:.5];
}];
//2.解壓
NSBlockOperation * op2 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"解壓---%@",[NSThread currentThread]);
[NSThread sleepForTimeInterval:1.0];
}];
//3.通知用戶
NSBlockOperation * op3 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"通知用戶---%@",[NSThread currentThread]);
}];
//NSOperation 提供了依賴關(guān)系
//注意,不要指定循環(huán)依賴,隊列就不工作了!!
[op2 addDependency:op1];
[op3 addDependency:op2];
//添加到隊列中 waitUntilFinished:是否等待! //會卡住當(dāng)前線程!
[self.opQueue addOperations:@[op1,op2,op3] waitUntilFinished:NO];
添加好依賴條件操作就會等待依賴的操作執(zhí)行完再執(zhí)行。