我想用一条新记录替换领域中的所有存在对象:
let realm = RLMRealm(path: ...)
let newRecord = MyRealm()
//... fill record
let existingJustNow = MyRealm.allObjectsInRealm(realm)
realm.beginWriteTransaction()
realm.addObject(newRecord) // first write new record
realm.commitWriteTransaction()
realm.beginWriteTransaction()
realm.deleteObjects(existingJustNow) // now delete the older ones
realm.commitWriteTransaction()
但这会删除所有对象(甚至是新对象)。
有没有办法停止allObjects方法的自动更新? 或者我要将结果复制到数组中并删除它吗?
答案 0 :(得分:1)
在这种情况下,您最好将RLMObjects复制到数组中,然后将其删除。
let realm = RLMRealm(path: ...)
let newRecord = MyRealm()
//... fill record
let existingJustNow = MyRealm.allObjectsInRealm(realm).valueForKey("self") as! [MyRealm]
realm.beginWriteTransaction()
realm.addObject(newRecord) // first write new record
realm.deleteObjects(existingJustNow) // now delete the older ones
realm.commitWriteTransaction()
好消息是,制作一个RLMObjects数组不必将所有内容从数据库复制到内存中,它们仍然是延迟加载的访问器,所以它非常轻量级。