【发布时间】:2017-12-30 15:11:24
【问题描述】:
问题:在Realm中修改单个对象时,RealmCollectionChange中的修改参数被传递多个索引
详细信息:给定一个包含 Dog 对象列表的 Person 对象和一个拥有 Person 类型的 owner 属性的 Dog 对象
class Dog: Object {
@objc dynamic var name = ""
@objc dynamic var owner: Person?
}
class Person: Object {
@objc dynamic var name = ""
let dogs = List<Dog>()
}
然后用两条狗创造一个人
let person0 = Person()
person0.personName = "Leroy"
let dog0 = Dog()
dog0.name = "Spot"
dog0.owner = person0
let dog1 = Dog()
dog1.name = "Rex"
dog1.owner = person0
person0.dogs.append(dog0)
person0.dogs.append(dog1)
//write person0 to Realm which creates the person and two dogs
还有观察功能
func doObserve() {
let realm = try! Realm()
let results = realm.objects(Dog.self)
notificationToken = results.observe { [weak self] (changes: RealmCollectionChange) in
switch changes {
case .initial:
case .update(_, let deletions, let insertions, let modifications):
for index in deletions {
print("deleted object at index: \(index)")
}
for index in insertions {
print("inserted object at index: \(index)")
}
for index in modifications {
print("modified object at index: \(index)")
let object = results[index]
print(object) //prints dog0 and dog1 when dog1 is mod
}
case .error(let error):
fatalError("\(error)")
}
}
}
那么,如果使用 RealmBrowser(或使用 App 中的代码)打开 Realm 文件并将 Dog1 (Rex) 名称更改为 Fluffy,则 RealmCollectionChange 中的修改参数包含两个索引,0 和 1,即使只有 dog1 (索引 1) 已修改。
这种行为是否正确,如果正确,是否有另一种选择来获取被修改的(索引)对象?
(或者我完全错过了一些明显的东西?)
【问题讨论】: