Swift - 如何在不迭代领域对象集合的情况下批量更新对象
Swift - How to update objects in bulk with out iterating over a collection of realm objects
我的 realmDB 中有将近十万条记录,每次用户根据同一 属性 中的另一个 属性 更改他的设备时区时,我想重新计算一个特定的 属性 =26=].
示例:
class Activity: Object {
// In UTC received from server
dynamic var effectiveDate: Date?
// Needs to be re-calculated everytime user launches the app based on `effectiveDate`
dynamic var effectiveDay: Date?
}
假设:我的领域 table 中有 100,000 个这样的 activity 记录,称为 Activities
此外,realm 指出,将 KVC 应用于集合是批量更新对象的好方法,而无需在为每个项目创建访问器时迭代集合的开销。
在我的例子中,我不想为每条记录设置相同的值,而是想使用 KVC 为每条记录基于 effectiveDate
属性 重新计算 effectiveDay
以避免迭代的开销。可能吗?
简答:
It is not possible without iterating over a collection of realm
objects.
长答案:
The realm is a model class based database. It does not support any
query (Predicates or Filter mostly used to retrieve data with a specific condition) like SQLite means We can't update all record in a single query by using the realm
. So answer of your question is pretty
straightforward, Without iterating we can not update the value.
如果要更改某些对象的值,可以提高性能。
代码:
let persons = realm.objects(Person.self).filter("id IN %@", ids)
try! realm.write {
persons.first?.setValue(true, forKeyPath: "isFirst")
// set each person's planet property to "Earth"
persons.setValue("Earth", forKeyPath: "planet")
}
我的 realmDB 中有将近十万条记录,每次用户根据同一 属性 中的另一个 属性 更改他的设备时区时,我想重新计算一个特定的 属性 =26=].
示例:
class Activity: Object {
// In UTC received from server
dynamic var effectiveDate: Date?
// Needs to be re-calculated everytime user launches the app based on `effectiveDate`
dynamic var effectiveDay: Date?
}
假设:我的领域 table 中有 100,000 个这样的 activity 记录,称为 Activities
此外,realm 指出,将 KVC 应用于集合是批量更新对象的好方法,而无需在为每个项目创建访问器时迭代集合的开销。
在我的例子中,我不想为每条记录设置相同的值,而是想使用 KVC 为每条记录基于 effectiveDate
属性 重新计算 effectiveDay
以避免迭代的开销。可能吗?
简答:
It is not possible without iterating over a collection of realm objects.
长答案:
The realm is a model class based database. It does not support any query (Predicates or Filter mostly used to retrieve data with a specific condition) like SQLite means We can't update all record in a single query by using the
realm
. So answer of your question is pretty straightforward, Without iterating we can not update the value.
如果要更改某些对象的值,可以提高性能。
代码:
let persons = realm.objects(Person.self).filter("id IN %@", ids)
try! realm.write {
persons.first?.setValue(true, forKeyPath: "isFirst")
// set each person's planet property to "Earth"
persons.setValue("Earth", forKeyPath: "planet")
}