我试图弄清楚如何删除从服务器api收到的本地存储的实体集。在这种情况下,我们假设在本地存储了10个实体,服务器向我发送了8个实体。其中6个对应于我本地已有的实体,2个是新的。本地我有4个“过时”的实体,因为服务器不提供它们。
当然,我可以删除所有内容并保存新实体,但我试图提高效率。
但是我不明白,一旦我创建了一个表示本地和远程情况之间差异的swift Set,我该如何删除本地对象,因为领域告诉我只能删除属于该领域的对象。
我尝试过使用结果集,但是我无法找到一种方法来过滤带有“IN”子句的对象,它提供了一组对象,即使我记得过去做过类似的事情。 / p>
let realm = try! Realm()
try! realm.write{
let oldEvents = Array(self.events!)
var newEvents = [Event]()
for event in events{
if let e = Mapper<Event>().map(JSONObject: event){
newEvents.append(e)
}
}
//here I create a set which contains the difference between remote and local entitites, and create an Array with them
let difference = Array(Set(newEvents).subtracting(Set(oldEvents)))
//this is obviously wrong
let objToDelete = realm.objects(Event.self).filter("event in %@", difference)
realm.delete(objToDelete)
//realm.delete(difference)->this gives the error that you can delete only objects that belong to the realm
//here I would like to create or update the new events
for newEvent in newEvents{
realm.create(Event.self, value: event, update: true)
}
}
对于如何处理这种情况,任何提示都会非常感激。谢谢!