NSOperation
- NSOperation的作用
- 配合使用NSOperation(操作)和NSOperationQueue(隊(duì)列)也可以實(shí)現(xiàn)多線程編程
- NSOperation和NSOperationQueue實(shí)現(xiàn)多線程的具體步驟
- 1.先將需要執(zhí)行的操作封裝到NSOperation對(duì)象中
- 2.將NSOperation對(duì)象添加到NSOperationQueue(隊(duì)列)中
- 3.系統(tǒng)會(huì)自動(dòng)將NSOperationQueue中的NSOperation取出來
- 4.將取出的NSOperation封裝的操作放到一條新線程中執(zhí)行
- (如果隊(duì)列的最大線程數(shù)為1的話,就不會(huì)創(chuàng)建新的線程)
NSOperationQueue的隊(duì)列類型
- 主隊(duì)列
- [NSOperationQueue mainQueue]
- 凡是添加到主隊(duì)列中的任務(wù)(NSOperation)炬搭,都會(huì)放到主線程中執(zhí)行
- 非主隊(duì)列(其他隊(duì)列)
- [[NSOperationQueue alloc] init]
- 同時(shí)包含了:串行呈宇、并發(fā)功能
- 添加到這種隊(duì)列中的任務(wù)(NSOperation),就會(huì)自動(dòng)放到子線程中執(zhí)行
如何創(chuàng)建隊(duì)列
//自己創(chuàng)建隊(duì)列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//獲取主隊(duì)列
NSOperationQueue *queue = [[NSOperationQueue mainQueue]
- 隊(duì)列的掛起屬性:
- 這個(gè)屬性決定是否把隊(duì)列里的任務(wù)掛起,但是任務(wù)是原子性的,不會(huì)馬上結(jié)束一個(gè)任務(wù),而是會(huì)當(dāng)前任務(wù)真正結(jié)束的時(shí)候才會(huì)被掛起
- @property (getter=isSuspended) BOOL suspended;
- 隊(duì)列的最大線程數(shù)屬性:
- 決定了這個(gè)隊(duì)列最多可以創(chuàng)建多少個(gè)線程
- @property NSInteger maxConcurrentOperationCount;
- 隊(duì)列添加任務(wù)的方法:
- 用這個(gè)方法添加進(jìn)隊(duì)列后,就會(huì)自動(dòng)開始任務(wù)
- (void)addOperation:(NSOperation *)op;
如何創(chuàng)建任務(wù)
//方式1,執(zhí)行這個(gè)任務(wù)的時(shí)候會(huì)自動(dòng)調(diào)用opRunOne這個(gè)自定義的函數(shù)
NSInvocationOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(opRunOne) object:nil];
//方式2
NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"op3------%@",[NSThread currentThread]);
}];
- 任務(wù)的開始方法:
- 一個(gè)任務(wù)可以自己寫成一個(gè)類,把要執(zhí)行的操作寫在下面這個(gè)函數(shù)里
- 任務(wù)的取消屬性以及方法:使用這個(gè)方法可以取消正在執(zhí)行的任務(wù)
- @property (readonly, getter=isCancelled) BOOL cancelled;
- (void)cancel;
- 任務(wù)添加依賴的方法:如果希望A任務(wù)在其他的任務(wù)都執(zhí)行完才執(zhí)行的話,就給A任務(wù)添加其他任務(wù)的依賴?yán)?[A addDependency:B];
- -(void)addDependency:(NSOperation *)op;
- 用這個(gè)方法添加的代碼會(huì)在自動(dòng)創(chuàng)建的一個(gè)新的線程里運(yùn)行:- (void)addExecutionBlock:(void (^)(void))block;
NSOperation線程間通信的方法
[[[NSOperationQueue alloc] init] addOperationWithBlock:^{
//在自定義的隊(duì)列中執(zhí)行的代碼
__block UIImageView *image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"123"]];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
//在main隊(duì)列中執(zhí)行的代碼
image = nil;
}];
}];
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者