Reputation: 1594
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?
Upvotes: 7
Views: 8224
Reputation: 134
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
Upvotes: 1
Reputation: 125
A solution would be to create a primary key that hashes the value. i.e. create a hash from the data that is reasonably unique. Hash the restaurant name and table names for instance.
Then you would have to have buckets for each hash value which would contain the restaurants that hit it.
If a newly entered restaurant has no existing hash, it can simply be added to the bucket, otherwise a check to see if it matches an existing restaurant in the bucket is needed to test for uniqueness.
Upvotes: 0
Reputation: 1787
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.
Upvotes: 4