【问题标题】:What is the difference between `Add` and `Create``Add` 和 `Create` 有什么区别
【发布时间】:2016-05-20 20:11:04
【问题描述】:

文档说明了显而易见的,即:

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.

但我看不出有什么区别?

【问题讨论】:

    标签: realm


    【解决方案1】:

    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)
        }
    

    【讨论】:

    • 就是这样。换句话说,不要像我一样,永远不要使用 add。
    【解决方案2】:

    add() 将传入的对象添加到 Realm(将对象修改为现在引用 Realm 中的数据),而 create() 在 Realm 中创建对象的副本并返回该副本,然后执行不修改参数。

    【讨论】:

    • 感谢您的回复。不过还不是很清楚。 add vs create 的典型用例是什么?
    猜你喜欢
    • 2016-04-02
    • 2013-06-11
    • 2020-01-19
    • 1970-01-01
    • 2011-01-12
    • 2019-07-03
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多