【发布时间】:2017-07-13 08:32:02
【问题描述】:
我正在尝试使用 Realm 将大约 8000 条记录保存到磁盘中,但它会阻塞 UI。因此,我使用Realm.asyncOpen 在后台线程中执行数据保存。
当我尝试以这种方式保存大量记录时,问题是 100% 的 CPU 使用率。
如何正确加载数千条记录到 Realm?
【问题讨论】:
我正在尝试使用 Realm 将大约 8000 条记录保存到磁盘中,但它会阻塞 UI。因此,我使用Realm.asyncOpen 在后台线程中执行数据保存。
当我尝试以这种方式保存大量记录时,问题是 100% 的 CPU 使用率。
如何正确加载数千条记录到 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()
}
}
}
【讨论】:
您是否尝试过批量保存数据?喜欢https://github.com/realm/realm-cocoa/issues/3494
- (void)startImport
{
NSLog(@"Staring Import");
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
RLMRealm *realm = [RLMRealm defaultRealm];
NSUInteger batch = 0;
NSUInteger total = 50000;
[realm beginWriteTransaction];
Feed *newFeed = [[Feed alloc] init];
[realm addObject:newFeed];
for (NSUInteger i = 0; i < total; i++)
{
FeedItem *newItem = [[FeedItem alloc] init];
newItem.feed = newFeed;
[newFeed.items addObject:newItem];
batch++;
if (batch == 100)
{
batch = 0;
[realm commitWriteTransaction];
NSLog(@"Committed Write Transaction, Saved %@ total items in Realm", @(i+1));
if (i < (total-1))
{
[realm beginWriteTransaction];
}
}
else if (i == (total-1))
{
[realm commitWriteTransaction];
NSLog(@"Committed Write Transaction, Saved %@ total items in Realm", @(i+1));
}
}
});
}
【讨论】: