Search code examples
realm

What is the difference between `Add` and `Create`


The documentation states the obvious i.e.:

add(_:update:) Adds or updates an object to be persisted it in this Realm.
create(_:value:update:) Creates or updates an instance of this object and adds it to the Realm populating the object with the given value.

but I can't quite see the difference if any ?


Solution

  • add will update whole object at once, so there is a danger that you may miss an attribute. create can update partial information of the object by displaying attribute names.

    Let's say cheeseBook is saved already as below.

        let cheeseBook = Book()
        cheeseBook.title = "cheese recipes"
        cheeseBook.price = 9000
        cheeseBook.id = 1
    
        //update 1 - title will be empty
        try! realm.write {
            let cheeseBook = Book()
            cheeseBook.price = 300
            cheeseBook.id = 1
            realm.add(cheeseBook, update:true)            
        }
    
        //update2 - title will stay as cheese recipes
        try! realm.write {
            realm.create(Book.self, value:["id":1, "price":300], update:true)
        }