MagicalRecord和CoreData保存在不同的上下文错误中

时间:2017-04-10 13:10:03

标签: ios objective-c core-data magicalrecord

所以我有一些方法可以使用MagicalRecord在CoreData中保存我的设置。但后来我试图这样做,我收到了这个错误:Illegal attempt to establish a relationship 'settings' between objects in different contexts

所以这是我的代码: 此方法是由特定用户保存数据,该用户现在正在使用programm

-(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");
    }];
}

此方法从CoreData为currentUser进行设置:

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

最后一个方法,从CoreData获取当前用户的userData:

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

我需要帮助才能认识到这是我的错误,因为对我而言,这似乎都是逻辑。

1 个答案:

答案 0 :(得分:0)

您在获取SettingsData时使用默认上下文。所以,改变:

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

为:

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

(免责声明:在浏览器中输入,未针对拼写错误进行测试)