gpt4 book ai didi

objective-c - 核心数据唯一性不起作用?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:44:59 26 4
gpt4 key购买 nike

当使用两个托管对象上下文时,我在处理单个上下文中同一实体的重复对象时遇到问题。

考虑以下代码:

[childMOC performBlockAndWait:^{

// CREATE PERSON IN CHILD MOC
Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person"
inManagedObjectContext:childMOC];

person.name = @"Ben";

// SAVE CHILD MOC TO PUSH CHANGES TO MAIN MOC
[childMOC save:nil];

NSManagedObjectID *personID = person.objectID;

[mainMOC performBlockAndWait:^{
// SAVE MAIN MOC TO PERSIST THE PERSON AND REPLACE ID TO PERMANENT
[mainMOC save:nil];

// GET THE PERSON IN THE MAIN MOC
Person *personInMainContext = (Person*)[mainMOC objectWithID:personID];

// GET THE PERSON'S NEW PERMANENT ID
NSManagedObjectID *personIdAfterSaveToPersistentStore = personInMainContext.objectID;

[childMOC performBlockAndWait:^{

// GET THE PERSON IN THE CHILD MOC WITH ITS NEW PERMANENT ID
// (this is common when sending the id from mainMOC to childMOC)
Person *samePersonFetchedFresh = (Person*)[childMOC objectWithID:personIdAfterSaveToPersistentStore];

// THE PERSON OBJECTS SHOULD BE EXACTLY THE SAME BECAUSE THE MOC GUARANTEES UNIQUING
samePersonFetchedFresh.name = @"Jerry";
NSLog(@"%@ & %@", person.name, samePersonFetchedFresh.name);

// OUTPUT: Ben & Jerry
// NOT THE SAME?!
}];
}];
}];

这意味着在子 MOC 中创建的对象在保存在主 MOC/持久存储中时会失去其唯一性。

谁能解释为什么 uniquing 在这种情况下不起作用?

最佳答案

在记录名字之前尝试刷新你的人物。我认为 uniquing 有效,但缓存失效可能无效。

关于objective-c - 核心数据唯一性不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11242919/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com