Permanent NSManagedObject URI from temporary URI?
I have an NSManagedObject subclass which stores URIs of child objects. It initially stores the temporary URI when a child object is first created, and implements -willSave
to call -obtainPermanentIDsForObjects
on its NSManagedObjectContext before saving, so that only the permanent ID is persisted.
The problem I'm running into, though, is that other instances also store the temporary URI. When one gets the -willSave
message shortly after another object with the same child do开发者_C百科es, it also calls -obtainPermanentIDsForObjects
and gets a different, wrong permanent URI, causing subsequent Core Data fault errors like:
CoreData could not fulfill a fault for '0x102e4c110 <x-coredata://E17EE19B-E7F3-4102-ACFF-3E6F8BE8B104/MyEntityName/p2>'
I would like a way to get from an NSManagedObject's old, temporary, URIRepresentation to its new, permanent, URIRepresentation that was already generated.
My initial thought is to store my own dictionary of <temporary URI,permanent URI>
and look up against that before using -obtainPermanentIDsForObjects
- is there an easier (more foolproof or built-in) way that I'm missing? Nothing I found in the documentation suggested anything.
I ended up getting a permanent ID with the -obtainPermanentIDsForObjects
call immediately after creating the child object, before it belongs to any parent. That way, the parent object never sees a temporary ID. This works, though I'm still anxious to hear if there are any better solutions.
Subscribe to your managed object context's NSManagedObjectContextDidSaveNotification
. Iterate through the objects in the NSInsertedObjectsKey
and get their managed object ids. At this point, they will all be the correct, permanent id and you can safely get the URI and store it.
精彩评论