iOS CoreData批量插入?

在我的iPhone应用程序中,我需要在核心数据中插入〜2000条logging,然后用户才能使用应用程序的任何function。 我从本地JSON文件加载到CoreData的logging。 这个过程需要很长时间(2.5+分钟),但是只需要一次(或者每个〜10个应用程序打开以获得更新的数据)。

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

如果我不能使用核心数据来加速它,那么其他推荐的选项是什么?

核心数据编程指南“中的” 高效导入数据“一章。

我现在和你有同样的问题,只能插入10000个物体,大约需要30秒,对我来说还是很慢的。 我在插入到上下文中的每1000个托pipe对象(换句话说,批量大小为1000)上执行[managedObjectContext保存]。 我已经尝试了30种不同的批量(从1到10000),在我的情况下1000似乎是最佳值。

当我遇到这个问题时,我正在寻找类似问题的答案。 @ 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() } } 

Objective-C的

@Suragch anwser的版本

 NSManagedObjectContext * MOC = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; MOC.persistentStoreCoordinator = YOURDB.persistentStoreCoordinator; [MOC performBlock:^{ // DO YOUR OPERATION }];