Search code examples
ioscore-datansmanagedobjectcontext

When Is obtainPermanentIDsForObjects:error: ever needed? from 2 different classes?


My understanding on the background of using this (2 different versions which varies on return values) method is: Managed-Objects created in memory by a MOC are first assigned temporary object IDs so that they may be uniquely identified without involving the persistent store. When a MOC is saved, however, the persistent store coordinator needs permanent object IDs for these Managed-objects. (correct me if I got wrong, please!)

I never used MOC's

- (BOOL)obtainPermanentIDsForObjects:(NSArray *)objects error:(NSError **)error

, but still call MOC's save: method without problems. However the code I used this week by 3rd party, uses this MOC's obtainPermanentIDsForObjects each time right after inserting a new Managed-object, is this really necessary?? Maybe needed for multithreading environment? But why Apple "CoreData PG" never mentioned this method? Has persistent-store-coordinator done it automatically for me just before saving MOC?

During research I saw another version of this method in NSIncrementalStore Class...

- (NSArray *)obtainPermanentIDsForObjects:(NSArray *)array error:(NSError **)error

, it says "This method is called (overridden in subclass then called, I guess) before executeRequest:withContext:error: with a save request, to assign permanent IDs to newly-inserted objects."

What should I do? Do I need to use both versions (NSIncrementalStore subclass's before save, and MOC's version right after new creation)? Which method is must called OR neither?

Thanks!


Solution

  • When an NSManagedObject is first inserted into an NSManagedObjectContext it has a temporary NSManagedObjectID. When the context is saved, the NSManagedObjectContext will do the equivalent of obtainPermanentIDsForObjects:error on NSManagedObjectContext, which in turn calls NSPersistentStoreCoordinator, which finds the store responsible for this object and calls obtainPermanentIDsForObjects:error on the store itself. This turns the NSManagedObject's temporary ID into a permanent one.

    NSManagedObjectIDs can be passed between NSManagedObjectContexts (if they share the same stores), but only if the NSManagedObjectID is a permanent ID. You can call obtainPermanentIDsForObjects:error to turn a temporary ID into a permanent ID independent of a save operation, but the store that the object belongs to may not expect that.