0

I am using the core data stack shown in the image below. I want to design a structure where objects can be created in both worker contexts.

What I am observing in the setup is if both contexts try to create the same object (for a unique key) at around the same time, db ends up in creating two rows for the table. Is there a way to solve this? Thanks in advance for your response.

enter image description here

Shashank
  • 1,743
  • 1
  • 14
  • 20

1 Answers1

0

The only way you can ensure uniqueness would be to have a coordinating object that all contexts turn to to verify their operation (a "uniqueness enforcer" if you will).

The general algorithm is described HERE, however you fall under the "multi-threaded/context" category and this will complicate things.

In a multi-threaded environment, your enforcer would have to perform a save to the store (using its own managed object context) before returning results to the calling object.

The general flow would be (no cache version):

  1. A context request object for keys from the enforcer
  2. The enforcer issue the request "under lock" (either locking an actual lock or using a serial dispatch queue)
    1. the enforcer query the store for existing objects
    2. create objects for missing keys and save them
      1. you might want to mark the objects as stubs, as the caller might not eventually save and it will give you a flag to ignore them in your fetch requests in your views
    3. build the results array with the objects he created
      1. the results might be NSManagedObjectIDs or imported objects in the caller context otherwise you risk cross context access of managed objects
Community
  • 1
  • 1
Dan Shelly
  • 5,991
  • 2
  • 22
  • 26