swift - How to save a realm relationship (list) -


i've had try save realm object database, it's not working.

here's models:

class creditcard: object {     dynamic var owner: string?     var purchases: list<purchase>() } 

and second class looks 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 creditcard objects fine.

on second view controller, have request, download purchases made credit card. after request how try write realm:

let creditcard = realm.objects(creditcard.self).first // there's code this.  try! realm.write {     purchase in purchases { // purchases = objects 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 reason purchases objects lost when app closes. purchases saved on realm objects, relationship between creditcard , purchase lost. so, return code below empty when re-open app:

let purchases = creditcard.purchases 

what doing wrong?

you need save purchases well, not in parent credit card object.

let creditcard = realm.objects(creditcard.self).first // there's code this.  try! realm.write {     purchase in purchases { // purchases = objects son         let newpurchase = purchase()         newpurchase.id = purchase["id"].intvalue         newpurchase.name = purchase["name"].stringvalue         newpurchase.date = purchase["date"].datevalue         realm.add(newpurchase) // <-- save purchase object realm          creditcard.purchases.append(newpurchase)     }  } 

the creditcard object exists in realm don't add again.


Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -