编写NSOperation友好的方法

时间:2010-12-13 18:49:02

标签: iphone ios nsoperation

我有一个对象(Processor),其中包含几个执行冗长计算的方法。我想在主线程和NSOperation子类中使用这些方法。

在我的NSOperation子类代码中,我反复调用isCancelled,因此取消响应非常快。但是,当操作调用其中一个冗长的Processor方法时,在该方法返回之前,它无法响应取消。

有没有一种很好的方法来编写方法,以便它们可以在有和没有操作的情况下使用?我正在考虑在我的CPU密集型operation方法中添加Processor参数并将其编写为:

- (void)calculateWithOperation:(NSOperation *)operation {
    do {
        if (operation != nil && [operation isCancelled]) {
            return;
        }
        // Do some more calculation...
    } while (! finished);
}

// For convenient main thread execution.
- (void)calculate {
    [self calculateWithOperation:nil];
}

之前是否有其他人遇到此问题?还有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

NSOperation响应取消的唯一方法是尽可能频繁地检查它是否被取消。毕竟,它只是一个在设置标志时需要退出的线程。基本上,需要isCancelled基础设施才能优雅地释放操作资源。所以我要说你只需用支票来加工昂贵的方法。

相关问题