【发布时间】:2018-07-18 11:02:35
【问题描述】:
我在名为 Verse 的关系中存储了近 7K 项。我有另一个名为 Translation 的关系,它需要通过来自 JSON 文件的单个调用来加载 7K 相关项目。
这是我的代码:
let container = getContainer()
container.performBackgroundTask() { (context) in
autoreleasepool {
for row in translations{
let t = Translation(context: context)
t.text = (row["text"]! as? String)!
t.lang = (row["lang"]! as? String)!
t.contentType = "Verse"
t.verse = VerseDao.findById(row["verse_id"] as! Int16, context: context)
// this needs to make a call to the database to retrieve the approparite Verse instance.
}
}
do {
try context.save()
} catch {
fatalError("Failure to save context: \(error)")
}
context.reset()
}
findById 方法的代码。
static func findById(_ id: Int16, context: NSManagedObjectContext) -> Verse{
let fetchRequest: NSFetchRequest<Verse>
fetchRequest = Verse.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "verseId == %@", id)
fetchRequest.includesPropertyValues = false
fetchRequest.fetchLimit = 1
do {
let results =
try context.fetch(fetchRequest)
return results[0]
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
return Verse()
}
}
在我添加VerseDao.findById 之前,这一切正常,这使得整个过程非常缓慢,因为它必须为每个对象向Coredata 数据库发出请求。
我尽我所能限制获取属性的数量并使用 NSFetchedResultsController 进行数据获取,但没有运气。
我想知道是否有任何方法可以更有效地插入子记录?谢谢。
【问题讨论】:
-
请向我们展示 VerseDao.findById 的代码。
-
@user3727099 已更新。谢谢。
-
不确定它是否有很大的不同,但你真的希望在给定
verseId的 findById 中找到多个对象,否则你可以跳过排序描述符 -
@JoakimDanielson 好点。我删除了它,但操作似乎仍然很慢。
-
按照答案之一的建议更新了 findById 的代码。
标签: swift performance core-data relationship