Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

realm

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 ?

like image 709
Running Turtle Avatar asked May 20 '16 20:05

Running Turtle


2 Answers

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)
    }
like image 106
oneman93 Avatar answered Dec 09 '22 07:12

oneman93


add() adds the passed-in object to the Realm (modifying the object to now refer to the data in the Realm), while create() creates a copy of the object in the Realm and returns that copy, and does not modify the argument.

like image 36
Thomas Goyne Avatar answered Dec 09 '22 06:12

Thomas Goyne