如何获取当前正在执行的NSOperation? [英] How to get hold of the currently executing NSOperation?

查看:223
本文介绍了如何获取当前正在执行的NSOperation?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于是否有 [NSOperationQueue currentQueue] [NSThread currentThread] NSOperation

Is there an equivalent to [NSOperationQueue currentQueue] or [NSThread currentThread] for NSOperation?

我有一个相当复杂的域模型,其中重型处理在调用栈中发生得很深。为了及时取消操作,我需要将 NSOperation 作为参数传递给每个方法,直到我想要中断一个更长的运行循环。使用线程我可以使用 [[NSThread currentThread] isCancelled] 所以似乎很方便,如果有一个等效的NSOperation,不幸的是只有看似无用的 [NSOperationQueue currentQueue]

I have a fairly complex domain model where the heavy processing happens quite deep down in the call stack. In order to timely cancel an operation I would need to pass the NSOperation as a parameter to every method until I get to the point where I want to interrupt a longer running loop. Using threads I could use [[NSThread currentThread] isCancelled] so it would seem convenient if there is an equivalent for NSOperation, unfortunately there is only the seemingly useless [NSOperationQueue currentQueue].

推荐答案

不,没有方法可以找到当前正在执行的操作。

No, there's no method to find the currently executing operation.

有两种方法可以解决您的问题:

Two ways to solve your problem:


  1. 。如果你需要对象A与对象B交谈,你需要安排A来引用B.有很多方法可以做到。一种方法是将操作传递给需要知道它的每个对象。另一个是使用委托。第三个是使一些更大的上下文的操作部分传递给每个方法或函数。如果你发现你需要传递一个引用从一个对象通过几个其他只是为了得到它最终将使用它的对象,这是一个线索你应该考虑重新安排你的代码。

  1. Operations are objects. If you need object A to talk to object B, you'll need to arrange for A to have a reference to B. There are lots of ways to do that. One way is to pass the operation along to each object that needs to know about it. Another is to use delegation. A third is to make the operation part of some larger "context" that's passed along to each method or function. If you find that you need to pass a reference from one object through several others just to get it to the object that will finally use it, that's a clue that you should think about rearranging your code.

让重型提升方法返回一些在调用链中传递的值。你不一定需要重型提升方法调用 [currentOperation cancel] 来完成你的目标。实际上,最好让它返回一些值,操作将理解为工作完成,现在停止,因为它可以检查返回值并立即退出,而不必调用 -

Have the "heavy lifting" method return some value that gets passed up the call chain. You don't necessarily need the heavy lifting method to call [currentOperation cancel] to accomplish your goal. In fact, it would be better to have it return some value that the operation will understand to mean "work is done, stop now" because it can check that return value and exit immediately rather than having to call -isCancelled once in a while to find out whether it has been cancelled.

这篇关于如何获取当前正在执行的NSOperation?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆