realm / realm-swift

Realm is a mobile database: a replacement for Core Data & SQLite
https://realm.io
Apache License 2.0
16.29k stars 2.14k forks source link

Is there any method to insert instances once a time? #2786

Closed yuldong closed 8 years ago

yuldong commented 8 years ago

define a class:

import <Realm/Realm.h>

@interface YYYProductInfo : RLMObject @property NSString name; @property NSInteger price; @property NSData productDescription; @property NSDate *date; @end RLM_ARRAY_TYPE(YYYProductInfo) then, we could insert a product to a realm like this:

YYYProductInfo *product = ...;
[... beginWriteTransaction];
[YYYProductInfo createInDefaultRealmWithValue:product];
[... commitWriteTransaction];

If I want to insert many products once a time, how could i do?

mrackwitz commented 8 years ago

First of all you should be aware that batching writes to larger transactions is the recommended way to go with Realm. There are different possibilities to achieve that. It could look like below:

RLMRealm *realm = [RLMRealm defaultRealm];
NSMutableArray *products = [NSMutableArray new];
for (NSDictionary *productData in …) {
     YYYProductInfo *product = …;
     [productArray addObject:product];
}
[realm transactionWithBlock:^{
     [realm addObjects:products];
}];

Alternatively you could also insert them one-by-one in a larger transaction:

RLMRealm *realm = [RLMRealm defaultRealm];
[realm transactionWithBlock:^{
     for (NSDictionary *productData in …) {
          YYYProductInfo *product = …;
          [realm addObject:product];
     }
}];

Does this answer your question?

yuldong commented 8 years ago

@mrackwitz thanks a lot, i just focus on the class of my own, and forget that RLMRealm also has method to do such thing. thank you very much.