Realm对象发生了变化,该对象的另一个副本也发生了变化,为什么?

时间:2016-06-16 19:10:23

标签: ios swift realm

我遇到了问题。让我们假设我有这个领域模型:

class Table: Object {
    dynamic var id = 0
    dynamic var x: Int = 0
    dynamic var y: Int = 0
    dynamic var width:Int = 0
    dynamic var height: Int = 0
    dynamic var text: String = ""
    dynamic var color: String = ""
    dynamic var type: String = ""

    let food = List<Food>()

    override static func primaryKey() -> String {
        return "id"
    }
}

class Food : Object {

    dynamic var id: Int = 0
    dynamic var name = ""
    dynamic var ingredients: String = "" // bigger text field
    dynamic var size: Int = 0 // none, small, medium, big size
    dynamic var price: Float = 0.0
    dynamic var category: Category?
    let additionalIngredients = List<Ingredient>()

    override static func primaryKey() -> String {
        return "id"
    }
}

假设我有一张桌子,并且在桌子上添加了相同食物的2倍,如下所示:

try! realm.write(){
    table.food.append(food) // A
    table.food.append(food) // B
    realm.add(table, update: true)
}

如果我更改食物A的附加成分,同样食物B也会更改其值。我正在通过此交易进行更改:

try! realm.write(){
    table.food.first!.additionalIngredients.removeAll()
    for ingredient in ingredientsToAdd{
        table.food.first!.additionalIngredients.append(ingredient)
    }
    realm.add(table, update: true)
}

我想我在参考/实例上做错了,有人可以给我一个提示吗?

提前致谢!

1 个答案:

答案 0 :(得分:3)

List.append()将对象本身添加到列表而不是对象的副本,因此您只有一个Food对象。