在我的iPhone应用程序中,我需要在Core Data中插入大约2000条记录,然后用户才能使用该应用程序的任何特性。我正在将记录从本地JSON文件加载到CoreData中。这个过程需要很长的时间(2.5+分钟),但只需要发生一次(或者每10个应用程序打开一次以获取更新的数据)。
核心数据是否有批量插入?如何加快此插入过程?
如果我不能使用Core Data加快速度,还有其他推荐的选项吗?
发布于 2010-11-10 15:56:22
查看核心数据编程指南中的Efficiently Importing Data章节。
我目前遇到了和你一样的问题,只是我插入了10000个对象,大约需要30秒,这对我来说仍然很慢。我对插入到上下文中的每1000个托管对象执行managedObjectContext保存(换句话说,我的批处理大小是1000)。我已经试验了30种不同的批处理大小(从1到10000),在我的例子中,1000似乎是最佳值。
发布于 2015-08-16 10:52:55
我在寻找a similar question的答案时遇到了这个问题。@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()
}
}
发布于 2017-03-23 08:39:49
Objective-C
@Suragch anwser的版本
NSManagedObjectContext * MOC = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
MOC.persistentStoreCoordinator = YOURDB.persistentStoreCoordinator;
[MOC performBlock:^{
// DO YOUR OPERATION
}];
https://stackoverflow.com/questions/4145888
复制