Search code examples
iosswift3realm

How to create a realm instance (having nested objects) from a dictionary?


For example, I have model class like this

class User: Objects {
    var firstName: String?
    var lastName: String?
    var friends: List<User>?

}

and Dictionary like this

{
   firstName : "Mohshin"
   lastName : "Shah"
   friends : [
              {
               firstName : "Friend 1"
               lastName : "abc"
               },
              {
               firstName : "Friend 2"
               lastName : "def"
               }
              ]
}

I want to make a User object using the dictionary. I have tried Realm' init(value: Any) method and it is creating the User with flat values only but not the friends is initiated.


Solution

  • The reason you're experiencing these issues is because the List<User> object must be initialized before use. Realm recommends declaring List and RealmOptional objects as let and therefore initializing them right inside the model.

    In addition to that, you need to declare other properties using the dynamic var attribute in order for the properties to become accessors for the underlying database.

    More on what I mentioned in the Property Attributes and Supported Types sections of our documentation. With all that said, I recommend you change your model to the following:

    import RealmSwift
    
    class User: Object {
        dynamic var firstName: String?
        dynamic var lastName: String?
        let friends = List<User>()
    }
    

    I hope this helps and please let me know if you need anymore assistance.