我尝试使用 Realm 将大约 8000 条记录保存到磁盘中,但它阻塞了 UI。结果,我用Realm.asyncOpen
在后台线程中执行数据保存。
当我尝试以这种方式保存大量记录时,问题是 CPU 使用率 100%。
如何正确加载数千条记录到Realm?
尝试官方demo中的方式保存大量数据:
DispatchQueue(label: "background").async {
autoreleasepool {
// Get realm and table instances for this thread
let realm = try! Realm()
// Break up the writing blocks into smaller portions
// by starting a new transaction
for idx1 in 0..<1000 {
realm.beginWrite()
// Add row via dictionary. Property order is ignored.
for idx2 in 0..<1000 {
realm.create(Person.self, value: [
"name": "\(idx1)",
"birthdate": Date(timeIntervalSince1970: TimeInterval(idx2))
])
}
// Commit the write transaction
// to make this data available to other threads
try! realm.commitWrite()
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)