自定义NSOperation并发的问题
想自己动手并发一个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的调用?