领域列表中的对象未更新
Object in Realm List is not updated
我有一个包含 MyGroup
列表的模型。
fileprivate let groups: List<MyGroup>
MyGroup
继承自 Realm 的 Object
。它有一个计算的 属性 percentage
和一个 属性 oldPercentage
用于存储最后计算的 属性。我不想将它保存到数据库中,所以我忽略了它。
class MyGroup: Object {
override static func ignoredProperties() -> [String] {
return ["oldPercentage"]
}
dynamic var oldPercentage: Double = 0
var percentage: Double {
//does some basic calculations
}
dynamic var name: String = ""
}
问题出在下面的代码片段中。
do {
let group = groups[indexPath.row]
//group.percentage = 0.5, group.name = "Hi"
try realm.write {
group.oldPercentage = group.percentage
print(group.oldPercentage) //prints 0.5
print(groups[indexPath.row].oldPercentage) //prints 0.0
groups[indexPath.row].oldPercentage = group.percentage
print(groups[indexPath.row].oldPercentage) //prints 0.0
groups[indexPath.row] = group
print(groups[indexPath.row].oldPercentage) //prints 0.0
group.name = "Test"
print(groups[indexPath.row].name) //prints "Test"
}
catch { ... }
我基本上想得到 group
,更改 oldPercentage
属性 并将其传递回我的 UICollectionView
。
我正在获取 indexPath
选择的 group
。这工作正常并给了我正确的 group
。然后,我想将 oldPercentage
的值更改为 percentage
。当我对局部变量 group
执行此操作时,它会正确更改其值。但是,groups
列表中的对象 未 更新。
我还尝试在不创建局部变量的情况下更改组的 oldPercentage
值。我没想到会出现与上述代码不同的行为,但确实没有。
我最后一次尝试是将成功打印正确 oldPercentage
的 group
对象分配给 indexPath
的组。也没用。
使用保存在数据库中的 name
属性 时,对象的行为符合预期并且值已正确更新。
我需要做什么才能在 List
中更新我的 group
?
Realm 忽略的属性特定于每个对象实例,并且每次索引一个 List
returns 一个新对象。您需要不忽略 oldPercentage
或将您设置 oldPercentage
的实例直接传递给需要读取它的对象。
我有一个包含 MyGroup
列表的模型。
fileprivate let groups: List<MyGroup>
MyGroup
继承自 Realm 的 Object
。它有一个计算的 属性 percentage
和一个 属性 oldPercentage
用于存储最后计算的 属性。我不想将它保存到数据库中,所以我忽略了它。
class MyGroup: Object {
override static func ignoredProperties() -> [String] {
return ["oldPercentage"]
}
dynamic var oldPercentage: Double = 0
var percentage: Double {
//does some basic calculations
}
dynamic var name: String = ""
}
问题出在下面的代码片段中。
do {
let group = groups[indexPath.row]
//group.percentage = 0.5, group.name = "Hi"
try realm.write {
group.oldPercentage = group.percentage
print(group.oldPercentage) //prints 0.5
print(groups[indexPath.row].oldPercentage) //prints 0.0
groups[indexPath.row].oldPercentage = group.percentage
print(groups[indexPath.row].oldPercentage) //prints 0.0
groups[indexPath.row] = group
print(groups[indexPath.row].oldPercentage) //prints 0.0
group.name = "Test"
print(groups[indexPath.row].name) //prints "Test"
}
catch { ... }
我基本上想得到 group
,更改 oldPercentage
属性 并将其传递回我的 UICollectionView
。
我正在获取 indexPath
选择的 group
。这工作正常并给了我正确的 group
。然后,我想将 oldPercentage
的值更改为 percentage
。当我对局部变量 group
执行此操作时,它会正确更改其值。但是,groups
列表中的对象 未 更新。
我还尝试在不创建局部变量的情况下更改组的 oldPercentage
值。我没想到会出现与上述代码不同的行为,但确实没有。
我最后一次尝试是将成功打印正确 oldPercentage
的 group
对象分配给 indexPath
的组。也没用。
使用保存在数据库中的 name
属性 时,对象的行为符合预期并且值已正确更新。
我需要做什么才能在 List
中更新我的 group
?
Realm 忽略的属性特定于每个对象实例,并且每次索引一个 List
returns 一个新对象。您需要不忽略 oldPercentage
或将您设置 oldPercentage
的实例直接传递给需要读取它的对象。