文档说明了明显的:
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.
Run Code Online (Sandbox Code Playgroud)
但我不能完全看出有什么不同吗?
one*_*n93 17
添加将立即更新整个对象,因此存在您可能错过属性的危险.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)
}
Run Code Online (Sandbox Code Playgroud)