iOS CoreData批量插入?

jam*_*mes 24 iphone core-data ios

在我的iPhone应用程序中,我需要在用户可以使用应用程序的任何功能之前将〜2000条记录插入到Core Data中.我将记录从本地JSON文件加载到CoreData.此过程需要很长时间(2.5分钟以上),但只需要发生一次(或每次打开10个应用程序以获取更新数据).

是否有核心数据的批量插入?我怎样才能加快这个插入过程?

如果我无法使用Core Data加速,那么其他推荐的选项是什么?

Vla*_*vic 28

查看"核心数据编程指南"中的" 高效导入数据"一章.

我目前遇到与你相同的问题,只是我插入10000个物体,它需要大约30秒,这对我来说仍然很慢.我正在对插入到上下文中的每1000个托管对象执行[managedObjectContext save](换句话说,我的批处理大小为1000).我已经尝试了30种不同的批量大小(从1到10000),在我的情况下,1000似乎是最佳值.

  • 啊,我正在为每个项目做保存.我没有意识到每个人都没有保存.在我的循环外移动`save`调用使它更快!下降到~5秒 (8认同)

Sur*_*gch 7

当我遇到这个时,我正在寻找类似问题的答案.@ VladimirMitrovic的答案当时有助于我知道我不应该每次都保存上下文,但我也在寻找一些示例代码.

现在我拥有它,我将提供下面的代码,以便其他人可以看到执行批量插入的样子.

// set up a managed object context just for the insert. This is in addition to the managed object context you may have in your App Delegate.
let managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = (UIApplication.sharedApplication().delegate as! AppDelegate).persistentStoreCoordinator // or wherever your coordinator is

managedObjectContext.performBlock { // runs asynchronously

    while(true) { // loop through each batch of inserts. Your implementation may vary.

        autoreleasepool { // auto release objects after the batch save

            let array: Array<MyManagedObject>? = getNextBatchOfObjects() // The MyManagedObject class is your entity class, probably named the same as MyEntity
            if array == nil { break } // there are no more objects to insert so stop looping through the batches

            // insert new entity object
            for item in array! {
                let newEntityObject = NSEntityDescription.insertNewObjectForEntityForName("MyEntity", inManagedObjectContext: managedObjectContext) as! MyManagedObject
                newObject.attribute1 = item.whatever
                newObject.attribute2 = item.whoever
                newObject.attribute3 = item.whenever
            }
        }

        // only save once per batch insert
        do {
            try managedObjectContext.save()
        } catch {
            print(error)
        }

        managedObjectContext.reset()
    }
}
Run Code Online (Sandbox Code Playgroud)