编写 NSOperation 友好的方法
我有一个对象(Processor
),其中包含多个执行冗长计算的方法。我想在主线程和 NSOperation 子类中使用这些方法。
在我的 NSOperation
子类代码中,我重复调用 isCancelled
,因此取消响应相当灵敏。但是,当操作调用这些冗长的 Processor 方法之一时,在该方法返回之前它无法响应取消。
有没有一种好的方法来编写方法,以便它们可以在有操作和没有操作的情况下使用?我正在考虑向我的 CPU 密集型 Processor
方法添加一个 operation
参数,并像这样编写它们:
- (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];
}
之前有其他人遇到过这个问题吗?有更好的办法吗?
I have an object (Processor
) containing several methods that perform lengthy calculations. I'd like to use those methods both on the main thread and in NSOperation
subclasses.
Inside my NSOperation
subclass code I repeatedly call isCancelled
, so cancellation is fairly responsive. However, when the operation calls one of those lengthy Processor
methods, it isn't able to respond to cancellation until that method returns.
Is there a good way to write methods so they can be used both with and without operations? I'm considering adding an operation
argument to my CPU-intensive Processor
methods and writing them like this:
- (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];
}
Has anyone else run into this issue before? Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
NSOperation 响应取消的唯一方法是尽可能频繁地检查 isCancelled 是否已取消。毕竟,它只是一个在设置标志时需要退出的线程。基本上,需要 isCancelled 基础设施来正常释放操作的资源。所以我想说你只需要在昂贵的方法中添加检查即可。
The only way for an NSOperation to respond to canceling is to check if it's isCancelled as frequently as feasible. After all, it's just a thread which needs to exit when a flag is set. Basically, the isCancelled infrastructure is needed to gracefully free the operation's resources. So I'd say you just have to pepper the expensive method with checks.