1

I have to create some data in CoreData entities in batch (import process) and I would like to "commit" at the end or "rollback" on an error (so saving inbetween won't work).

The problem is that I for example need to create an entity "Person" and later in that progress I need to re-use that entity. BUT it can already exists BEFORE this process or may be created WHILE this import process.

So I'm trying to fetch it with a predicate "(personId == 4711)". But although I have set [fetchRequest setIncludesPendingChanges:YES]; it doesn't find the newly created Person object.

I read this this question and this answer which state, that it is not possible? Am I right?

If so, how can I workaround / handle this?

4

1 回答 1

1

根据我对 CoreData 的了解,这确实是不可能的(如果我错了,请纠正我)。

然而,即使这是可能的,您也永远不想在“每个对象”的基础上查询您的商店。
对大型(几十个)进口的性能影响是巨大的。

我对您的建议是在导入阶段创建一个由您的唯一标识符键入的字典(从存储现有实体中预取并为不存在的实体创建新实体)。

注意:您应该注意不要在多线程环境中执行来自不同上下文的多次插入。在这种情况下,您将需要一名协调员来防止重复。

例子:

存储内容:1 --> P1, 3 --> P3
服务响应:1 --> Data1, 2 --> Data2

算法:
响应完成时,从响应中获取所有唯一 ID --> recievedIds= @[1,2]
在创建recievedIds集合期间创建 personId 的映射/字典 --> 数据:
@{1:Data1,2:Data2}

通过谓词从存储中获取:
[NSPredicate predicateWithFormat:@"personId IN %@",recievedIds]
从结果数组创建字典。
在这种情况下:existingItems= @{1 : P1}

传递以下所有 id recievedIds
1)如果 id 存在于existingItems更新现有对象
2)否则创建一个新人员并将数据插入新记录。

这只会从商店中获取一次。
而且您只保存一次。
==> 去商店只有 2 次,而不是每个对象一次

于 2013-09-18T13:44:45.123 回答