MkaysWork MkaysWork - 4 months ago 78x
Swift Question

Realm object changed, another copy of that object has changed too, why?

I am stuck in a problem. Let's assume I have this Realm Model:

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"

Let's say I have one table and added 2 times the same food on that table like so :

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

If I change the additionalIngredients for food A , also at the same food B changes its values. I am doing that changes with this transaction :

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

I guess I am doing something wrong regarding the reference/instance, can someone give me a hint?

Thanks in advance!


List.append() adds the object itself to the list and not a copy of the object, so you only have one Food object.