Magical Record添加对象,不同的上下文错误 [英] Magical Record add object, different context error

查看:128
本文介绍了Magical Record添加对象,不同的上下文错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程式中使用Magical Record,并且想为使用者新增「Note」的功能,这是「entry」的子项。



我添加了此代码:

  [MagicalRecord saveWithBlock:^(NSManagedObjectContext * localContext){
Note * newNote = [Note MR_createInContext:localContext];

newNote.content = noteContent;
newNote.name = @User Note;

[self.entry addNotesObject:newNote];
}
完成:^(BOOL成功,NSError *错误){
if(error!= nil)
{
// show alert
}
else if(success)
{
[[self tableView] reloadData];
}
}];

我最后一行的错误是非法尝试建立一个关系'对象在不同的​​上下文



我试图将'entry'和'newNote'的上下文设置为'localContext',但我仍然得到相同的错误。 >

我失踪了什么?

解决方案

条目是在不同的上下文中创建的,因此您无法从此条目访问它。
而不是:

  [self.entry addNotesObject:newNote]; 

您应该首先找到 self.entry object localContext

  [[self.entry MR_inContext:localContext] addNotesObject :newNote]; 

您可以在并发环境中找到使用MagicalRecord的解释,在线程上执行核心数据操作。虽然很短,但在我看来,值得阅读核心数据编程指南,即使您不直接使用CD。


I'm using Magical Record in my app, and want to add the functionality for a user to add a 'Note', which is a child of 'entry'.

I added this code:

    [MagicalRecord saveWithBlock: ^(NSManagedObjectContext *localContext) {
        Note *newNote = [Note MR_createInContext: localContext];

        newNote.content = noteContent;
        newNote.name = @"User Note";

        [self.entry addNotesObject: newNote];
     }
                      completion: ^(BOOL success, NSError *error) {
                          if (error != nil)
                          {
                              // show alert
                          }
                          else if (success)
                          {
                              [[self tableView] reloadData];
                          }
                      }];

The error I keep getting on the last line is "Illegal attempt to establish a relationship 'entry' between objects in different contexts"

I tried setting the context of both 'entry' and 'newNote' to 'localContext', but I still get the same error.

What am I missing?

解决方案

self.entry was created in different context, so you can't access it from this one. Instead of:

[self.entry addNotesObject: newNote];

you should first find self.entry object in localContext:

[[self.entry MR_inContext:localContext] addNotesObject: newNote];

You can find an explanation of using MagicalRecord in a concurrent environment at Performing Core Data operations on Threads. Though it's quite short, so in my opinion it's worthwhile to read Core Data Programming Guide even though you don't use CD directly.

这篇关于Magical Record添加对象,不同的上下文错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆