简体   繁体   English

Realm Swift如何更新List对象

[英]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 . 日期由Date()生成,并转换为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. 如果下一个值具有相同的Date我想更新现有的eatenCalories属性,如果Date不同,我想创建另一个记录到数据库。

Any ideas? 有任何想法吗?

Now after each value adding it create another record in DB. 现在,在每个值添加之后,在数据库中创建另一个记录。

BR iMat BR iMat

Adds or updates an existing object into the Realm. 将现有对象添加或更新到领域中。 Only pass true to update if the object has a primary key. 仅当对象具有主键时才传递true以进行更新。 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) self.realm.add(item,update:true)

and you should add primary key to your object 并且应该将主键添加到对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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