automaticMergesChangesFromParent不执行任何操作

时间:2019-04-14 17:32:28

标签: ios core-data

我正在观看有关某些“新”更改的WWDC 2016(Core Data的新功能)视频,在某些时候,有人说这个新属性automaticallyMergesChangesFromParent应该自动合并来自父级的更改。子上下文。

我创建了一个简单的测试用例:

CustomObject *customObject = [[CustomObject alloc] initWithContext:self.persistentContainer.viewContext];
customObject.name = @"TEST";
customObject.customID = 2252;
self.persistentContainer.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy;

NSManagedObjectContext *firstContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
firstContext.parentContext = self.persistentContainer.viewContext;
firstContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy;
firstContext.automaticallyMergesChangesFromParent = YES;

CustomObject *contextObj = [firstContext objectWithID:customObject.objectID];
NSLog(@"NAME [%@]", contextObj.name);
customObject.name = @"JO";
[self.persistentContainer.viewContext save:NULL];
NSLog(@"NAME [%@]", contextObj.name);

输出为:

 NAME [TEST]
 NAME [TEST]

我希望是这样:

NAME [TEST]
NAME [JO]

如果我使用[firstContext refreshAllObjects];,它将按预期工作,但是如果automaticallyMergesChangesFromParent设置为YES或NO,则没有区别。

我想知道这应该如何工作吗? documentation并没有太大帮助。

谢谢。

2 个答案:

答案 0 :(得分:1)

您正在firstContext中获取和更新对象。要验证automaticallyMergesChangesFromParent,您应该从self.persistentContainer.viewContext获取并进行更新。

self.secondObject = [[SecondCustomObject alloc] initWithContext:self.persistentContainer.viewContext];
self.secondObject.name = @"TEST";
self.persistentContainer.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy;



NSManagedObjectContext *firstContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
firstContext.parentContext = self.persistentContainer.viewContext;
firstContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy;
firstContext.automaticallyMergesChangesFromParent = YES;
//firstContext.stalenessInterval = 0;

SecondCustomObject *contextObj = [self.persistentContainer.viewContext objectWithID:self.secondObject.objectID];
NSLog(@"NAME [%@]", contextObj.name);
contextObj.name = @"JO";
[self.persistentContainer.viewContext save:NULL];
SecondCustomObject * contextObj1 = [firstContext objectWithID:self.secondObject.objectID];
NSLog(@"NAME [%@]", contextObj.name);
NSLog(@"NAME [%@]", contextObj1.name);


 NAME [TEST]
 NAME [JO]
 NAME [JO]

答案 1 :(得分:1)

当您设置automaticallyMergesChangesFromParent = YES;并在父上下文中进行保存时,CoreData会通过在子队列上分派此块(通过照常调用mergeChangesFromContextDidSaveNotification:)在子上下文上自动调用performBlock: 。 当两个上下文都在主队列上工作后,您只会在下一个主循环上看到更改

尝试

CustomObject *contextObj = [firstContext objectWithID:customObject.objectID];
NSLog(@"NAME [%@]", contextObj.name);
customObject.name = @"JO";
[self.persistentContainer.viewContext save:NULL];
dispatch_async(dispatch_get_main_queue(), ^{
   NSLog(@"NAME [%@]", contextObj.name);
});