Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load thousands records to Realm correctly?

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?

like image 705
Vlad Khambir Avatar asked Mar 09 '23 15:03

Vlad Khambir


1 Answers

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()
    }
  }
}
like image 167
Yun CHEN Avatar answered Mar 20 '23 13:03

Yun CHEN