Search code examples
iosswiftrealm

How to create initial Realm objects that get added upon installation of app


Say I am creating an object that takes two strings and acts like a dictionary.

class WordInDictionary: Object {
    @objc dynamic var word: String = ""
    @objc dynamic var meaning: String = ""

What should I do if I wanted to have some initial objects that get added to the database just once upon installation/update of the app?

Also, is there a way to make it so that just those initial objects can't be deleted?


Solution

  • "What should I do if I wanted to have some initial objects that get added to the database just once upon installation/update of the app?"

    One option would be to have some code near the realm initialisation that checks if there are any WordInDictionary objects already in the realm - if not then add the required default objects.

    E.g.

    let realm = try! Realm()
    if realm.objects(WordInDictionary.self).isEmpty
    {
      // Add required words here
    }
    

    "Also, is there a way to make it so that just those initial objects can't be deleted?"

    I don't know of a way to make realm objects read-only. You'd have to implement this in code in some way, e.g. have a isDeletable boolean member which is true for every user-created object and false for your default members, then only delete those from realm.

    E.g. for your deletion code:

    func deleteWords(wordsToDelete: Results<WordInDictionary>)
    {
      try! realm.write 
      {
        realm.delete(wordsToDelete.filter("isDeletable = true")
      }
    }