mrcurious mrcurious - 1 year ago 130
iOS Question

Core Data objectID is nil after save

I have an a core data object I'm accessing it through its

. After saving this object to Core Data the objectId is nil, how can I get the newly updatedObject from Core Data, there is a uniqueID for this object but I doesn't exist at this point in the lifecycle.

Any help would be most appreciated, I've been trying for hours.


Answer Source

When the new entity is inserted into core data context it receives the temporary identifier. It will be replaced by permanent id when the context been saved. If you need to obtain the object id before this, you can get it using method:

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

This method converts the object ID of each managed object in objects to a permanent ID. Although the object will have a permanent ID, it will still respond positively to isInserted until it is saved. Any object that already has a permanent ID is ignored.


To get permanent id you need to do the following:

// Say you have inserted new managed object you want to get permanent ID of. 
// If you check current objectID after that it will be temporary ID.
NSManagedObject *obj = [NSEntityDescription insertNewObjectForEntityForName:kSomeEntityName inManagedObjectContext:ctx];

// After you have inserted new managed object into the context 
// (or an array of objects) try to obtain permanent Ids.
if (![ctx obtainPermanentIDsForObjects:@[obj] error:&err]) {
    // The operation fails. Handle an error.
    NSLog(@"Could not obtain permanent ID for object %@, error %@ %@", obj, err, err.userInfo);

// Now object ID of inserted object is permanent and it will not be
// changed during save operation. Store permanent ID for future use
NSManagedObjectID *objID = [obj objectID];