2017-07-13 5 views
3

レルムを使用してディスクに約8000のレコードを保存しようとしていますが、UIをブロックしています。その結果、バックグラウンドスレッドでデータを保存するRealm.asyncOpenを使用します。レルムに何千ものレコードを正しくロードするには?

大量のレコードをこの方法で保存しようとすると、100%CPU使用率が問題になります。

レルムに何千ものレコードを正しくロードするにはどうすればいいですか?

答えて

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

あなたはバッチでデータを保存しようとしたことがありますか? 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)); 
      } 
     } 
    }); 
} 
関連する問題