该文档指出了明显的地方,即:
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.
但是我看不出有什么区别吗?
最佳答案
add会立即更新整个对象,因此有可能会丢失属性。 create可以通过显示属性名称来更新对象的部分信息。
比方说,cheeseBook已被保存如下。
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)
}