4

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.

KudoCC
  • 6,912
  • 1
  • 24
  • 53

1 Answers1

4

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.

TiM
  • 15,812
  • 4
  • 51
  • 79
  • `refresh` seems not work if there is not a runloop in the thread. – KudoCC Feb 11 '17 at 02:17
  • `autorefresh` doesn't work in threads because it relies on the runloop mechanism. `refresh` is there to explicitly force a refresh in those instances. – TiM Feb 11 '17 at 02:20
  • Wow, it works. Thanks for your help. BTW I'm thinking about use NSThread to do the work, because NSOperationQueue seems to use many threads, even I set `maxConcurrentOperationCount ` to 1, if every one thread has a snapshot, it must consume a lot of memory and Cpu time. – KudoCC Feb 11 '17 at 02:31
  • Awesome! Thanks for that! Hmm, that's tricky. `NSOperationQueue` should be really efficient since it's just a Cocoa layer on top of GCD. You probably shouldn't use NSThreads unless you can quantifiably demonstrate that you'll get better performance out of them. http://stackoverflow.com/questions/9238135/grand-central-dispatch-vs-nsthreads – TiM Feb 11 '17 at 02:39
  • Yes, I'll use GCD as far as possible. I print out the thread pointer in my operation and find that there are about 10 different threads runs my operations, in my operation I modify the realm object so I must have a snapshot of db, if there are 10 threads have run my operations, I will have 10 snapshot... – KudoCC Feb 11 '17 at 02:47