自定义NSOperation并发的问题

rollrock1987 rollrock1987 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
想自己动手并发一个NSOperation,但是问题好大。
实现代码如下

#import "NSOperationA.h"

@interface NSOperationA()
{
BOOL isfihish;
BOOL isexcuting;
}
@end

@implementation NSOperationA

-(BOOL)isConcurrent{
return YES;
}
-(BOOL)isExecuting{
NSLog(@"isExecuting:%d",isexcuting);
return isexcuting;
}

-(BOOL)isFinished{
NSLog(@"isFinished:%d",isfihish);
return isfihish;
}

-(void)start{
if( [self isCancelled] ){
[self willChangeValueForKey:@"isFinished"];
isfihish = YES;
[self didChangeValueForKey:@"isFinished"];

NSLog(@"start- isCancelled");
}
else{
[self willChangeValueForKey:@"isExecuting"];
isexcuting = YES;
[self runLoop];
[self didChangeValueForKey:@"isExecuting"];
}
}

-(void)cancelSelf{
[self willChangeValueForKey:@"isFinished"];
isfihish = YES;
[self didChangeValueForKey:@"isFinished"];
}

-(void)runLoop{
while (![self isCancelled]) {
NSLog(@"runLoop");

[NSThread sleepForTimeInterval:1];
}
NSLog(@"runloop is canceled");
}

@end


调用代码如下:


//
NSOperationA*a;
////
a = [[NSOperationA alloc]init];
NSOperationQueue * q = [[NSOperationQueue alloc]init];
[q addOperation:a];
[self performSelector:@selector(cancelA) withObject:nil afterDelay:3];

//
-(void)cancelA
{
[a cancelSelf];
}

问题来了:
上面的代码打出来的log是这样的:
runloop
runloop
runloop
isFinished:1
runloop
runloop
N个runloop。

请问
1.为什么没有频繁的调用isFinished 跟isExecuting
2.为什么明明调用了cancelSelf,但是[self isCancelled] 依然是0.

如果将 [self runloop] 修改为[NSThread detachNewThreadSelector:@selector(runLoop) toTarget:self withObject:nil];
log如下:
runLoop
isExecuting:1
isFinished:0
runLoop
runLoop
isFinished:1
runLoop
runLoop
runLoop

问题:
1.为何这里会多了几次 isExecuting 跟 isFiished的调用?
...全文
评论 1
收藏 已收藏
分享
返回顶部
rollrock1987
iOS 29,038 成员 12,459 内容