I’m looking for a CoreData design pattern that will ensure a thread-safe “fetch or create”. I have a situation where two different threads may be looking for the same record at the same time. If this record isn’t found, then one gets created by the thread. Unfortunately, both threads don’t find this record, so they both create the same one.
I’m looking for a CoreData design pattern that will ensure a thread-safe fetch or
Share
T Reddy,
One way to do this is using a private queued MOC to do all creations — a creation MOC, if you will. This way you can do your fetch from whichever MOC you desire and, if it fails, you re-perform the fetch on the creation MOC and if it fails there then create it. This discipline will force you to always have in-order test and no duplicate creations. You will need to manage cross MOC coordination through either a child MOC relationship or through the “did save” merge notifications.
Andrew