Search code examples
realmnsoperationqueue

How to force a NSOperationQueue runs on one thread?


I am working with Realm, I would get/set realm object's property from different operations which are added to one NSOperationQueue.

Let's say in operation0, I set the realm object's property to a new value, then I add operation1 to the same operation queue, the operation1 fetch the realm object's property which may get the old value because the thread run operation1 may different from operation0.

How can I solve this ? Any suggestion will be appreciate.


Solution

  • It sounds like you need to make a guarantee that operation1 will only begin execution after operation0 has successfully completed setting the Realm write transaction.

    There are 2 ways you could potentially handle this:

    1. Make the operation queue serial. Set the maxConcurrentOperationCount property of the queue to 1, so that even if you add the operations to the queue at the same time, they'll only be executed in the order in which they were added.

    2. Make operation1 dependent on operation0. If you need to keep the operation queue concurrent, you can use NSOperation.addDependency(_:) to explicitly make sure that operation1 will only begin once operation0 has completed.

    In operation1, make sure you call refresh() on the Realm object you're using to fetch your Realm object in order to make absolutely sure that the changes you made in operation0 have been properly exposed on that queue.