多線程 - 3
NSOperation
NSOperation的使用
創(chuàng)建NSOperationQueue
NSOperation *queue = [[NSOperationQueue alloc] init];
創(chuàng)建NSOperation子類對象
NSOperation *operation = [[NSOperation alloc] init];
需要重寫NSOperation任務(wù)執(zhí)行函數(shù)谐宙。
MyOperation *operation = [[MyOperation alloc] init];
將NSOperation加入NSOperationQueue
[queue addOperation:operation];
ios為了讓我們更好的使用NSOperation定血,自定義了很多繼承類
NSBlockOperation
+ (instancetype)blockOperationWithBlock:(void(^)(void))block;
NSInvocationOperation
- (nullable instancetype)initWithTarget:(id)target selector:(SEL)sel object:(nullable id)arg;
NSOperation并發(fā)數(shù)
系統(tǒng)默認(rèn)提供:
@property NSInteger maxConcurrentOperationCount;
// = 1時舞虱,為Serial Queue
// > 1時喜爷,為Concurrent Queue
@property (readonly)NSUInteger operationCount;
//表示當(dāng)前正在執(zhí)行的queue中有多少任務(wù)。
GCD vs NSOperation
NSOperation支持取消够坐。封裝寸宵,能適應(yīng)更復(fù)雜的操作和提供更精細(xì)化的控制崖面。
屏幕快照 2017-07-18 下午11.45.55.png
既是queue被cancel了,最終仍會被執(zhí)行梯影。
等待
NSOperation不需要group的概念巫员。
- (void)waitUntilFinished;
- (void)waitUntilAllOperationsAreFinished;
Dependency
@interface NSOperation : NSObject {
- (void)addDependency:(NSOperation *)op;
- (void)removeDependency:(NSOperation *)op;
}
@property (readonly, copy)NSArray<NSOperation *>*dependencies;
循環(huán)依賴
顯示循環(huán)依賴
隱式循環(huán)依賴
屏幕快照 2017-07-19 上午2.30.25.png
優(yōu)先級
@property NSOperationQueuePriority queuePriority;
Operation進(jìn)入queue的原則是先進(jìn)先出。但當(dāng)優(yōu)先級大的operation準(zhǔn)備進(jìn)入queue時甲棍,它會插隊(duì)到比他小的operation前面简识。但不會替換掉正在執(zhí)行的operation。
NSOperationQueue常用屬性
@property (getter = isSuspended)BOOL suspended;
@property (nullable, copy)NSString *name;
@property NSQualityOfService qualityOfService;
總結(jié):
NSOperation和NSOperationQueue的基本概念
自定義NSOperation子類
NSOperation狀態(tài)和取消
NSOperation Dependency
waitUntilFinished
name感猛,優(yōu)先級七扰,暫停