如何正确加载数千条记录到 Realm? [英] How to load thousands records to Realm correctly?
本文介绍了如何正确加载数千条记录到 Realm?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 Realm 将大约 8000 条记录保存到磁盘中,但它阻止了 UI.因此,我使用 Realm.asyncOpen
在后台线程中执行数据保存.
I'm trying to save about 8000 records into the disk, using Realm, but it's blocking UI. As a result, I use Realm.asyncOpen
that performs data saving in background thread.
当我尝试以这种方式保存大量记录时,问题是 100% 的 CPU 使用率.
The problem is 100% CPU usage when I try to save big amount of records this manner.
如何正确加载数千条记录到 Realm?
How to load thousands records to Realm correctly?
推荐答案
试试官方demo中的方式来保存大量数据:
Try the way in official demo to save large amounts of data:
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()
}
}
}
这篇关于如何正确加载数千条记录到 Realm?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文