I have a Realm object called Restaurant
in my app. This Restaurant
object has lots of Table
objects connected to it. If I save on, it looks like this:
Restaurant *restaurant = [[Restaurant alloc] init];
restaurant.url = [_userData url];
restaurant.type = [_userData kind];
for (int i = 0; i < [[_userData tables] count]; i++) {
Input *input = [[_userData tables] objectAtIndex:i];
Table *table = [[Table alloc] init];
table.title = input.title;
table.seats = input.seats;
table.type = input.type;
[restaurant.tables addObject:table];
}
RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
config.fileURL = [NSURL URLWithString:[Preferences getRealmPath]];
RLMRealm *realm = [RLMRealm realmWithConfiguration:config error:nil];
[realm beginWriteTransaction];
[realm addObject:restaurant];
[realm commitWriteTransaction];
Now, what I want is that when a restaurant is added, but it already exists in that configuration, it's not stored. But when the same restaurant is added, but something is different - even if it's the amount of seats at 1 table - it should be added. What's the best way to achieve this?
Realm supports something called primary keys, which seem like a good fit for your problem.
A primary key is a unique identifier for an Realm object; it can be an integer or a string. In your case, you might use the URL as the primary key (if each restaurant is indeed associated with only one URL), or add a new property to serve as the primary key (perhaps a name
field).
You can then use the addOrUpdateObject:
method instead of the addObject:
method. This method only works for object types with primary keys.
In your case, assuming you set up a primary key for your Restaurant
model type, Realm would do one of the following:
Restaurant
was previously added to the Realm and has not changed relative to your new model, nothing will change.Restaurant
was previously added to the Realm but your model has since changed, the existing model in the Realm will be updated.Restaurant
wasn't previously added to the Realm, it will be added.Hope that helps.
Update to this: You no longer need to have different syntax when adding. Make sure a primary key exists and Realm will do the rest in terms of updating. Link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With