How to load thousands records to Realm correctly?

孤街醉人 提交于 2019-11-29 10:23:09

问题


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.

The problem is 100% CPU usage when I try to save big amount of records this manner.

How to load thousands records to Realm correctly?


回答1:


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()
    }
  }
}



回答2:


Have you tried to save data in batches ? like 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));
            }
        }
    });
}


来源:https://stackoverflow.com/questions/45075407/how-to-load-thousands-records-to-realm-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!