Search code examples
iosnsoperationnsoperationqueue

Make NSOperations Mutually exclusive


Refer this video from WWDC https://developer.apple.com/videos/play/wwdc2015/226/ The speaker shows that we can add dependency between two NSopeation instances of same type. Example an NSoperation that displays an alert. By achieving this we can make sure that we don't throw multiple alerts at same time and annoy the user. If one alert is already being displayed next one will wait.

I still can't figure out how to implement this dependency of NSOperations cross queue.In more simpler words can anyone show an example(implementation) of following two things.

1.Implementation of adding dependency of operation B from queue 2 on operation A from queue 1.

2.Implementation of adding dependency of multiple instances of same NSOperation type, even if they are in different queue. Example: if i add multiple instances of "AlertOperation" to different queue I want to make sure they still take place sequentially among themselves.

I would appreciate if the examples are in Objective C. Please ask for more clarification if needed.


Solution

  • I'm the engineer who presented that session.

    The short answer is that in order to make your second operation dependent on the first operation, you have to maintain a reference to the first operation.

    The sample code provided with the session uses a global table that keeps track of all the currently-executing operations. When a new operation comes in that specifies it should be mutually exclusive with other operations of the same kind, the code looks up in the table for the other operations of the same kind. The new operation is then made dependent on the last one in the list.

    Since the table is a global table, it works regardless of which queue the operations are actually executing on. The only thing it requires is using the custom NSOperationQueue subclass ("OperationQueue") as the thing that's executing operations.