jam*_*mes 24 iphone core-data ios
在我的iPhone应用程序中,我需要在用户可以使用应用程序的任何功能之前将〜2000条记录插入到Core Data中.我将记录从本地JSON文件加载到CoreData.此过程需要很长时间(2.5分钟以上),但只需要发生一次(或每次打开10个应用程序以获取更新数据).
是否有核心数据的批量插入?我怎样才能加快这个插入过程?
如果我无法使用Core Data加速,那么其他推荐的选项是什么?
当我遇到这个时,我正在寻找类似问题的答案.@ 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)
| 归档时间: |
|
| 查看次数: |
17395 次 |
| 最近记录: |