hdoria hdoria - 24 days ago 12
Swift Question

How to save a realm relationship (list)

I've had try to save a realm object to my database, but it's not working.

Here's my models:

class CreditCard: Object {
dynamic var owner: String?
var purchases: List<Purchase>()
}


And second class which looks like that:

class Purchase: Object {
dynamic var id: Int = 0
dynamic var name: String?
dynamic var data: String?
let creditCard = LinkingObjects(fromType: CreditCard.self, property: "purchases")
}


I can save all CreditCard objects just fine.

On a second view controller, I have another request, to download all purchases made by a credit card. After the request this is how I try to write to realm:

let creditCard = realm.objects(CreditCard.self).first // there's some code to get this.
try! realm.write {
for purchase in purchases { // purchases = objects from a son
let newPurchase = Purchase()
newPurchase.id = purchase["Id"].intValue
newPurchase.name = purchase["name"].stringValue
newPurchase.date = purchase["date"].dateValue

creditCard.purchases.append(newPurchase)
realm.add(creditCard, update: true)
}
}


For some reason all purchases objects are lost when the app closes. The purchases are saved on my realm objects, but the relationship between CreditCard and Purchase is lost. So, the return from the code below is always empty when I re-open the app:

let purchases = creditCard.purchases


What am I doing wrong?

Answer

You need to save the purchases as well, not only in the parent credit card object.

let creditCard = realm.objects(CreditCard.self).first // there's some code to get this. 
try! realm.write {
    for purchase in purchases { // purchases = objects from a son
        let newPurchase = Purchase()
        newPurchase.id = purchase["Id"].intValue
        newPurchase.name = purchase["name"].stringValue
        newPurchase.date = purchase["date"].dateValue
        realm.add(newPurchase) // <-- save the purchase object to realm

        creditCard.purchases.append(newPurchase)
    }
 }

The creditcard object already exists in the realm so don't add it again.

Comments