有没有办法一次保存 NSManagedObjects 1

时间:2021-06-30 13:41:55

标签: ios objective-c core-data magicalrecord

我遇到了这个问题,我有一个包含 NSManagedObjects 的 NSMutableArray。

我想迭代每个 NSManagedObject,为变量设置一个值,然后保存它们。

问题是我有一个验证以查看对象是否在数据库中,并且在我将我的第一个 NSManagedObject 保存到数据库之后,该数组中的所有其他 NSManagedObjects 也被插入到数据库中...

这是一段描述我的问题的代码:

for (Category* c in categories) {
    Category* original = [Database getCategoryByID:c.categoryid];
    // After the first save this will have value because it saves all the objects
    // that are in categories Array and the version will be the same...
    
    if (original != nil && original.version >= c.version) {
        // This object is already up to date so do not make any changes
    } else {
        // This object is not up to date, or it does not exist
        // update it's contents
        c.name = name;
        
        [[c managedObjectContext] MR_saveToPersistentStoreAndWait]; 
        // Here it saves all the objects instead of only 1 object
    }
}

有没有办法一次只保存 1 个对象,同时在 NSMutableArray 中有其他 NSManagedObjects ?

1 个答案:

答案 0 :(得分:2)

使用 Core Data,你告诉上下文要保存,它会保存它所拥有的一切。没有办法只保存一个对象,除非该对象是上下文中唯一一个发生变化的对象。

在您的情况下,您的 Category 对象数组似乎是托管对象,并且它们属于托管对象上下文。避免意外保存的最简单方法是将保存命令移动到循环之后。当你到达那个点时,

  • 任何需要创建或更新的 Category 都可以保存
  • 任何不需要更新的 Category 都没有变化,因此不会受到保存上下文的影响。

因此,将所有内容保存在上下文中应该是安全的。如果它有变化,它就会更新,如果没有,它就不会改变。

相关问题