Search code examples
iosobjective-ccore-datamagicalrecord

MagicalRecord and CoreData saving in different context error


So I have some methods to save my settings in CoreData by using MagicalRecord. But then I am trying to do this, I get this error: Illegal attempt to establish a relationship 'settings' between objects in different contexts

So here is my code: This method is saving data by specific user, who is using programm now

-(void)saveSettingsFirst:(BOOL)first{
    [MagicalRecord saveWithBlockAndWait:^(NSManagedObjectContext *localContext){
        SettingsData *newData = [self settingsDataForCurrentUserInContext:localContext];

        //SettingsData *newData = [SettingsData MR_createEntityInContext:localContext];
        newData.firstValue = @(first);
        NSLog(first ? @"saveSettings FIRST 0" : @"saveSettings FIRST 1");
        newData.settings = [[CacheManager shared] currentUserWithContext:localContext];

        NSLog(@"Settings one is saved");
    }];
}

This method is taking setting from CoreData for currentUser:

-(SettingsData*)settingsDataForCurrentUserInContext:(NSManagedObjectContext*)context{
    NSLog(@"In settingsDataForCurrentUserInContext");
    SettingsData *settings = [SettingsData MR_findFirstByAttribute:@"settings" withValue:[[CacheManager shared] currentUserWithContext:context]];
    return settings;
}

And finally method, who fetching userData for current user from CoreData:

-(UserData*)currentUserWithContext:(NSManagedObjectContext*)context{
    UserData *persons = [UserData MR_findFirstInContext:context];
    if (persons!=nil) {
        NSLog(@"Current user with context not nil value");
    }
    return persons;
}

I need help to recognize were is my mistake, because for me all it seems logic.


Solution

  • You are using the default context when fetching your SettingsData. So, change:

    SettingsData *settings = [SettingsData MR_findFirstByAttribute:@"settings" withValue:[[CacheManager shared] currentUserWithContext:context]];

    to:

    SettingsData *settings = [SettingsData MR_findFirstByAttribute:@"settings" withValue:[[CacheManager shared] currentUserWithContext:context] inContext: context];

    (disclaimer: typed in browser, not tested for typo's)