保存对象时使用MagicalRecord执行错误访问

时间:2014-10-10 16:19:34

标签: ios objective-c core-data nsmanagedobjectcontext magicalrecord

我在保存对象时遇到了使用MagicalRecord的问题。

使用以下方法保存上下文:

    - (void)saveContext {
    [[NSManagedObjectContext defaultContext] saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
        if (success) {
            NSLog(@"You successfully saved your context.");
        } else if (error) {
            NSLog(@"Error saving context: %@", error.description);
        }
    }];
}

此原因导致我的应用随机[[self MR_defaultContext] mergeChangesFromContextDidSaveNotification:notification];

上使用EXEC_BAD_ACCESS崩溃

我使用了其他方法:

//get correct order based on indexPath
Order *orderToComplete = [self objectInOrdersAtIndex:indexPath.section];
//set order as completed
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext)
 {
     Order *localOrder = [orderToComplete inContext:localContext];
     [localOrder setIsCompletedValue:YES];
 }completion:^(BOOL success, NSError *error)
 {
     if(success)
         NSLog(@"You successfully saved your context.");
     else
         NSLog(@"Error saving context: %@", error.description);
 }];

但仍然随机崩溃。

我的应用不是多线程应用。 这是一个镜头: enter image description here

有没有人有任何想法?

1 个答案:

答案 0 :(得分:0)

我可以解决我的问题。但找不到确切的原因。

你应该遵循的步骤

  1. 清除目标方法中的所有代码,只创建一个对象并保存?能省吗?如果是这样的话:
  2. 添加您的代码并逐步测试它您可以在代码中找到它,managedObjectStore将转到不一致状态。对我来说,这是因为调用委托方法。我在委托方法调用之后放了[NSManagedObjectContext saveContext]。它修好了
  3. 我正在使用2.2版 我可以找到问题发生的地方,但我不明白为什么! 但我在这做: 新项目将从网络推送到设备,因此如果它是第一个记录,则应自动选择该单元格。然后我调用detailsView控制器委托setItems来更新它的项目。之后,KVO将通知有关更改并尝试更新tableView: 想象没有记录,新项目将被推送到设备,其子项目将通过委托方法添加到detailsViewController

    self.subItems = subItems;

    landscape

    步骤: 1-更新视图 2-保存上下文

    委托方法在每次推送中调用两次。 然后KVO注意到subItems NSKeyValueChangeSetting发生了变化 在第二次推送之后,如果第二次推送包含新的子项KVO第一次注意到项目subItemsNSKeyValueChangeInsertion中有一个插入,那么正如我所说的委托方法调用两次,KVO注意到有一个更改NSKeyValueChangeSetting。在重新加载表应用程序崩溃后的这一步!

    NSNumber *kind = [change objectForKey:NSKeyValueChangeKindKey];
            //if we are setting new items to the items array; i.e. when we select a new row
            if ([kind integerValue] == NSKeyValueChangeSetting) {
                // adding the all the new items at top of the tableView
                NSArray *newItems = [change valueForKey:@"new"];
                [self.tableView reloadData];
    
            }
            //if we are adding one new order to the orders array
            else if ([kind integerValue] == NSKeyValueChangeInsertion)
            {
                // adding the new order at top of the tableView
                [self.tableView insertSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationTop];
            }
    

    最后我尝试了一次调用的委托来解决这个崩溃问题。但我无法理解为什么会发生上述错误!

    https://github.com/magicalpanda/MagicalRecord/issues/877