【问题标题】:MagicalRecord and CoreData saving in different context errorMagicalRecord 和 CoreData 保存在不同的上下文错误中
【发布时间】:2017-09-05 13:14:22
【问题描述】:

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

这是我的代码: 此方法是由正在使用程序的特定用户保存数据

-(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;
}

我需要帮助来认识到这是我的错误,因为对我来说这一切似乎都是合乎逻辑的。

【问题讨论】:

    标签: ios objective-c core-data magicalrecord


    【解决方案1】:

    在获取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];

    (免责声明:在浏览器中输入,未测试错字)

    【讨论】:

    • 好吧,它有效!谢谢!您能否解释或提供链接以阅读为什么这样做有效。因为我已经在使用上下文加载用户并且它成功加载。但正如我所见,我们需要在相同的上下文中进行搜索,对吧?
    • 是的,始终使用相同的上下文。如果您检查 MR 代码,您将看到我们的原始行使用默认上下文。但是您传递的是本地上下文,因此您应该对此进行调整。
    • 很高兴为您提供帮助,如果此答案解决了您的问题,请单击答案旁边的复选标记将其标记为已接受。请参阅:meta.stackexchange.com/questions/5234/… 了解更多信息
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多