Magical Record add object, different context error

前提是你 提交于 2019-12-07 16:48:36

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/19165704/magical-record-add-object-different-context-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!