简体   繁体   中英

Realm Swift How to update an List object

I have a problem when I try to update a value on a List. This is my DB model:

class User: Object {

@objc dynamic var id : Int = 0
@objc dynamic var height : Int = 0
@objc dynamic var age : Int = 0
@objc dynamic var sex : String = ""
@objc dynamic var physicalActivity : Double = 1.0
@objc dynamic var goal : String = ""
let weightProgress = List<WeightProgress>()
let calories = List<Calories>()

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

}
}


class Calories : Object {

@objc dynamic var date : String?
@objc dynamic var eatenCalories : Int = 0

}

The main feature is, User put how many calories he ate, and save it to DB. Date is generated by Date() and convert to String . If next value has the same Date I want to updated existing eatenCalories property, if Date is different I want to create another record to DB.

Any ideas?

Now after each value adding it create another record in DB.

BR iMat

Adds or updates an existing object into the Realm. Only pass true to update if the object has a primary key. If no object exists in the Realm with the same primary key value, the object is inserted. Otherwise, the existing object is updated with any changed values.

you should use

self.realm.add(item, update: true)

and you should add primary key to your object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM