如何停止当前的 NSOperation?
我使用 NSOperationQueue
和 NSOperation
在后台点击时运行某些函数。 但我希望能够,当用户单击某个按钮时,停止该操作。
我该怎么做呢?
类似于,[当前操作停止];
取消
- 对我不起作用。我想立即停下来。
谢谢
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该调用
-cancel
方法,并且操作本身必须支持通过监视isCancelled
属性/键路径来取消操作,并在其值变为YES 时安全停止
。如果 NSOperation 是您自己的,您可能必须创建一个自定义子类来实现此功能。您无法(安全地)强制立即停止任意操作。它必须支持被取消。You should be calling the
-cancel
method, and the operation itself has to support being cancelled by monitoring theisCancelled
property/keypath and safely stopping when its value becomesYES
. 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.您无法通过使用 Apple 通过
NSOperation
提供的任何内容立即停止。您可以按照其他人的建议使用-[cancel]
,但当前操作仍将运行直到完成。一种接近在操作内部使用-[isCancelled]
并将其散布在整个代码中的方法(尤其是在长时间运行的循环中)。比如:这样你就能相对较快地停止事情。
如果您希望真正强制线程停止,则可能需要研究信号处理。这里有一个线程示例。将自定义信号发送到特定线程,然后您可以以某种方式终止该线程。不过,这将需要做更多的工作,而且可能带来的麻烦比其价值要多得多。
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: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.
您使用
cancel
,并测试self
(NSOperation
)是否在执行过程中被取消。you use
cancel
, and test whetherself
(theNSOperation
) has been cancelled during execution.