如何停止当前的 NSOperation?

发布于 2024-12-10 21:09:07 字数 206 浏览 0 评论 0原文

我使用 NSOperationQueueNSOperation 在后台点击时运行某些函数。 但我希望能够,当用户单击某个按钮时,停止该操作。

我该怎么做呢?

类似于,[当前操作停止];
取消 - 对我不起作用。我想立即停下来。

谢谢

I'm using NSOperationQueue, and NSOperation for running some function on background click.
But I want to be able, when user clicks some button, stop that Operation.

How can I do it?

Something like, [currentoperation stop];
Cancel - won't work me. I want to stop immediately.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

只为守护你 2024-12-17 21:09:07

您应该调用 -cancel 方法,并且操作本身必须支持通过监视 isCancelled 属性/键路径来取消操作,并在其值变为 YES 时安全停止。如果 NSOperation 是您自己的,您可能必须创建一个自定义子类来实现此功能。您无法(安全地)强制立即停止任意操作。它必须支持被取消。

You should be calling the -cancel method, and the operation itself has to support being cancelled by monitoring the isCancelled property/keypath and safely stopping when its value becomes YES. If the NSOperation is your own, you will probably have to create a custom subclass to implement this functionality. You cannot (safely) force an arbitrary operation to immediately stop. It has to support being cancelled.

三月梨花 2024-12-17 21:09:07

您无法通过使用 Apple 通过 NSOperation 提供的任何内容立即停止。您可以按照其他人的建议使用 -[cancel] ,但当前操作仍将运行直到完成。一种接近在操作内部使用 -[isCancelled] 并将其散布在整个代码中的方法(尤其是在长时间运行的循环中)。比如:

- (void)main {
    // do a little work
    if ([self isCancelled]) { return; }

    // do a little more work
    if ([self isCancelled]) { return; }
}

这样你就能相对较快地停止事情。

如果您希望真正强制线程停止,则可能需要研究信号处理。这里有一个线程示例。将自定义信号发送到特定线程,然后您可以以某种方式终止该线程。不过,这将需要做更多的工作,而且可能带来的麻烦比其价值要多得多。

You can't stop immediately by using anything Apple provides with NSOperation. You can use -[cancel] as other people have suggested here, but the current operation will still run until completion. One way of getting close to use -[isCancelled] inside of your operation and sprinkle that throughout the code (especially in long running loops). Something like:

- (void)main {
    // do a little work
    if ([self isCancelled]) { return; }

    // do a little more work
    if ([self isCancelled]) { return; }
}

This way you'll get things stopped relatively soon.

If you're looking to really force the thread to stop, you may need to look into signal handling. There's a threaded example here. Sending a custom signal to a specific thread, you may be able to then terminate that thread in some way. This will be a lot more work, though, and is probably much more trouble than it's worth.

慢慢从新开始 2024-12-17 21:09:07

您使用cancel,并测试selfNSOperation)是否在执行过程中被取消。

you use cancel, and test whether self (the NSOperation) has been cancelled during execution.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文