保存在子上下文中会自动保存到父上下文

时间:2014-02-22 07:31:08

标签: ios core-data

我正在尝试创建一个更新功能,该功能还允许用户取消该过程。 我正在使用父子managedObjectContext,我已将父竞赛并发设置为NSMainQueueConcurrencyType。我的计划是不调用父上下文的save来取消更新。当我测试我的理论并注释掉所说的保存行时,我发现托管对象仍然更新。我做错了什么?

部分更新功能代码:

NSManagedObjectContext *bgContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[bgContext setParentContext:self.managedObjectContext];
[bgContext setUndoManager:nil];

[bgContext performBlockAndWait:^{

    for (NSDictionary *itemDictionary in items) {
        //update cancelled
        if (status == -1) {
            return;
        }

        //Function to get a single managedObject by querying the main context.
        NSArray *array = [self queryEntity:entityName withResId:[dictionary objectForKey:@"res_id"]];

        //get the object id of queried managedobject; context -> mainContext
        ENTITY *object = (ENTITY *)[context objectWithID:[[array firstObject] objectID]];
        object.data = @"something"; //change data

        count++;

        //save every 100
        if(count%100 == 0) {
            [bgContext performBlockAndWait:^{
                NSError *error;
                if(![bgContext save:&error]) {
                    NSLog(@"insert error child: %@", [error localizedDescription]);
                }
            }];
        }
    }

    //save excess
    if(count%100 != 0) {
        [bgContext performBlockAndWait:^{
            NSError *error;
            if(![bgContext save:&error]) {
                NSLog(@"insert error child: %@", [error localizedDescription]);
            }
        }];
    }

    //comment out to prevent saving to parent
    /*[context performBlockAndWait:^{
        NSError *error;
        if(![context save:&error]) {
            NSLog(@"insert error parent: %@", [error localizedDescription]);
        }
    }];*/
}];

1 个答案:

答案 0 :(得分:1)

发现我的问题。感谢这篇文章:https://stackoverflow.com/a/7825536/2260928
我使用这些行忽略取消的更改:

[bgContext reset];
[context reset];