Search code examples
iosobjective-cmagicalrecord

MagicalRecord - Retrieve the last inserted record id


I'm using MagicalRecord and I can not understand with and retrieve the id of the record you just saved

Items *item = [Items MR_createEntity];
item.ref_user = ref_user;
[self saveContext];



- (void)saveContext {
    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
        if (success) {
            DDLogInfo(@"MR_saveContext success");
            [self loadView];
            [self viewDidLoad];
        } else if (error) {
            DDLogError(@"Error saving context: %@", error.description);
        }
    }];
}

Solution

  • Why not just create it out of block?

    item = [ITEM MR_createEntityInContext:defaultContext];
    [defaultContext MR_saveToPersistentStoreAndWait];
    
    // you can retrieve the id of above item here