Ios 如何将数千条记录正确加载到域?
我试图使用Realm将大约8000条记录保存到磁盘中,但它阻塞了UI。因此,我使用在后台线程中执行数据保存的Ios 如何将数千条记录正确加载到域?,ios,swift,swift3,realm,Ios,Swift,Swift3,Realm,我试图使用Realm将大约8000条记录保存到磁盘中,但它阻塞了UI。因此,我使用在后台线程中执行数据保存的Realm.asyncOpen 问题是,当我试图以这种方式保存大量记录时,CPU使用率为100% 如何将数千条记录正确加载到域?在官方演示中尝试保存大量数据的方法: DispatchQueue(label: "background").async { autoreleasepool { // Get realm and table instances for this thre
Realm.asyncOpen
问题是,当我试图以这种方式保存大量记录时,CPU使用率为100%
如何将数千条记录正确加载到域?在官方演示中尝试保存大量数据的方法:
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()
}
}
}
DispatchQueue(标签:“后台”).async{
自动释放池{
//获取此线程的领域和表实例
让realm=try!realm()
//将书写块分成更小的部分
//通过启动新事务
对于0..中的idx1,您是否尝试过成批保存数据?例如
—(无效)startImport
{
NSLog(“启动导入”);
调度异步(调度获取全局队列(调度队列优先级高,0)^{
RLMRealm*realm=[RLMRealm defaultRealm];
整数批=0;
整数总数=50000;
[realm beginWriteTransaction];
Feed*newFeed=[[Feed alloc]init];
[realm addObject:newFeed];
对于(整数i=0;i
- (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));
}
}
});
}