简体   繁体   中英

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.

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.

From the comments, the underlying question is:

how can I add a dependency to an existing operation when I don't have a reference to it

You should create multiple different queues, and specifically in this case a queue just for alert operations. Technically it can work with a single queue, but you need to do a bit more work.

With a specific queue you can simply iterate the operations currently on the queue and add a dependency to every one. If you don't have a specific queue then you'll need to do a class test (or use some other logic) to decide exactly which operations to add a dependency to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM