【发布时间】:2011-04-21 01:15:26
【问题描述】:
我找不到关于如何将NSOperation 子类化为并发并支持取消的良好文档。我阅读了 Apple 文档,但找不到“官方”示例。
这是我的源代码:
@synthesize isExecuting = _isExecuting;
@synthesize isFinished = _isFinished;
@synthesize isCancelled = _isCancelled;
- (BOOL)isConcurrent
{
return YES;
}
- (void)start
{
/* WHY SHOULD I PUT THIS ?
if (![NSThread isMainThread])
{
[self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO];
return;
}
*/
[self willChangeValueForKey:@"isExecuting"];
_isExecuting = YES;
[self didChangeValueForKey:@"isExecuting"];
if (_isCancelled == YES)
{
NSLog(@"** OPERATION CANCELED **");
}
else
{
NSLog(@"Operation started.");
sleep(1);
[self finish];
}
}
- (void)finish
{
NSLog(@"operationfinished.");
[self willChangeValueForKey:@"isExecuting"];
[self willChangeValueForKey:@"isFinished"];
_isExecuting = NO;
_isFinished = YES;
[self didChangeValueForKey:@"isExecuting"];
[self didChangeValueForKey:@"isFinished"];
if (_isCancelled == YES)
{
NSLog(@"** OPERATION CANCELED **");
}
}
在我找到的示例中,我不明白为什么要使用 performSelectorOnMainThread:。它会阻止我的操作同时运行。
此外,当我注释掉该行时,我的操作会同时运行。但是,isCancelled 标志没有被修改,即使我调用了cancelAllOperations。
【问题讨论】:
标签: iphone nsoperation nsoperationqueue performselector