Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Realm object already exists

I have a Realm object called Restaurantin 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?

like image 862
user4992124 Avatar asked Jul 31 '16 18:07

user4992124


2 Answers

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:

  • If the Restaurant was previously added to the Realm and has not changed relative to your new model, nothing will change.
  • If the Restaurant was previously added to the Realm but your model has since changed, the existing model in the Realm will be updated.
  • If the Restaurant wasn't previously added to the Realm, it will be added.

Hope that helps.

like image 146
AustinZ Avatar answered Sep 20 '22 21:09

AustinZ


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

like image 40
Liam Bolling Avatar answered Sep 20 '22 21:09

Liam Bolling