Check if Realm object already exists

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.