How to get hold of the currently executing NSOperation? How to get hold of the currently executing NSOperation? multithreading multithreading

How to get hold of the currently executing NSOperation?


Came up with an extension in swift that returns the running operations

extension NSOperationQueue {    public var runningOperations: [NSOperation] {        return operations.filter {$0.executing && !$0.finished && !$0.cancelled}    }}

You can then pick up the first one

if let operation = aQueue.runningOperations.first {}


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

Two ways to solve your problem:

  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.

  2. 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.


This isn't a good idea. Operations are usually canceled by their queue. Within the operation's main() method, you can periodically check if self is cancelled (say, every n trips through a loop, or at the start of every major block of commands) and abort if so.

To respond to a cancellation (say, some UI element tied to the operation's or queue's status), you use key value observing (KVO) to have your controller observe the operations' started, completion, and cancelled properties (as needed), then set your UI's state (always on the main thread) when those keys are updated. Per JeremyP's comments, it's important to note the KVO notifications come from the op's thread and UI should (almost) always be manipulated on the main thread, so you'll need to use -performSelectorOnMainThread... methods to update your actual UI when you receive a state change KVO note about your operations.

What are you really trying to do? That is, why do you feel other parts of your app need to know directly about the current operation?