2017-07-13 29 views
3

我試圖使用Realm將大約8000條記錄保存到磁盤中,但它阻止了UI。因此,我使用在後臺線程中執行數據保存的Realm.asyncOpen如何正確加載數千條記錄到Realm?

當我嘗試以這種方式保存大量記錄時,問題是100%的CPU使用率。

如何正確加載數千條記錄到Realm?

回答

4

嘗試在官方演示的方式來保存大量的數據:

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

您是否嘗試過將數據保存在批?像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)); 
      } 
     } 
    }); 
}