Drux
Drux

Reputation: 12670

NSManagedObjects that have been inserted but not yet saved?

Is is possible to identify (at runtime) NSManagedObjects that have been inserted into a NSManagedObjectContext (i.e. inserted == YES) but have never been saved to the context's store so far.

I first thought their objectID may still be nil but this turned out not to be the case.

UPDATE I have conducted a quick experiment to see if checking temporaryID (see accepted answer) also works for nested MOCs. This suggests no: saving the child MOC pushes only one level up (i.e. to parent MOC but not to persistent store, which is further up), hence the object ID for a newly inserted MO remains temporary. One way to determine whether a MO is new in the child MOC and has never been saved (not even to the parent MOC) in this case is apparently checking for [child objectRegisteredForID: object.objectID] && ![parent objectRegisteredForID: object.objectID] instead.

Upvotes: 2

Views: 143

Answers (1)

Michał Ciuba
Michał Ciuba

Reputation: 7944

You can use temporaryID property of NSManagedObjectID:

YES if the receiver is temporary, otherwise NO. Most object IDs return NO. New objects inserted into a managed object context are assigned a temporary ID which is replaced with a permanent one once the object gets saved to a persistent store.

Example usage:

if(object.objectID.isTemporaryID) {
  //the object has not been saved yet
}

Upvotes: 2

Related Questions