从后台恢复后访问核心数据NSManagedObject会使应用程序崩溃

Oys*_*sio 6 core-data objective-c ios objective-c-blocks

我正在使用核心数据,并发现应用程序有时会在从后台恢复后崩溃.当我尝试访问NSManagedObject子类的属性时,我已经确定了块方法体内发生的崩溃.

我有一个属性,其中包含NSManagedObject对子类的引用.

@property(非原子,强)CalItem*calObject;

为了重现崩溃,我首先需要调用子viewController(NoteViewController)传递一个块(NoteTextBlock).

NoteViewController *noteViewController = [[NoteViewController alloc]initWithNote:self.calObject.note NoteTextBlock:^(NSString *noteText) {
                    self.calObject.note = noteText;  //crashing here
                }];
Run Code Online (Sandbox Code Playgroud)

然后将应用程序发送到后台并恢复它.然后在NoteViewController中,我将向调用viewController返回一条消息.

if (self.noteTextBlock)
{
 self.noteTextBlock(trimmedString);
}
Run Code Online (Sandbox Code Playgroud)

当块返回并且该行self.calObject.note = noteText被执行时,应用程序崩溃.

显然你不能把一个块放在堆栈上,然后恢复应用程序,然后继续使用块内定义的内容?或者我在这里做错了什么?

编辑:
*** Terminating app due to uncaught exception 'NSObjectInaccessibleException', reason: 'CoreData could not fulfill a fault for '0xb253100 <x-coredata://C2304B7C-7D51-4453-9993-D33B9113A7A5/DTODay/p57>''

这个块在子viewController中定义如下:

@property(nonatomic, copy)NoteTextBlock noteTextBlock;
Run Code Online (Sandbox Code Playgroud)

Edit2
这是我在崩溃的行上设置断点时得到的结果.
(lldb) po self.calObject
$2 = 0x0b4464d0 <DTODay: 0xb4464d0> (entity: DTODay; id: 0xb489d00 <x-coredata://C2304B7C-7D51-4453-9993-D33B9113A7A5/DTODay/p57> ; data: <fault>)

我正在使用MagicalRecord lib来管理所有Core Data的东西.

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    if ([NSManagedObjectContext MR_defaultContext] == nil
        || [NSManagedObjectModel MR_defaultManagedObjectModel] == nil
        || [NSPersistentStoreCoordinator MR_defaultStoreCoordinator] == nil
        || [NSPersistentStore MR_defaultPersistentStore] == nil
        )
    {
        //coming back from background, re-init coredata stack
        [MagicalRecordHelpers setupCoreDataStackWithAutoMigratingSqliteStoreNamed:DBNAME];
    }
Run Code Online (Sandbox Code Playgroud)

Dan*_*lly 2

我对 MagicalRecords 不熟悉,但是......

当您有一个无故障的(如 Edit2 中所示)对象不再(或从未存在)在存储中时,会引发此异常。
在某些情况下可能会发生这种情况:

  1. 另一个上下文已将其从商店中删除
  2. 您已插入它,为其获取了永久 ID,并且:
    ** 刷新它
    ** 保存它(但仅限于父上下文),重置父对象,并刷新当前上下文中的对象(或将其作为错误导入到您的主要上下文),参见objectWithID:

可能还有其他我忘记或不知道的情况。

如果您可以描述您的堆栈结构以及您的对象状态/起源,我们也许能够更好地理解问题