Swift Remove Object from Realm

后端 未结 6 1171
庸人自扰
庸人自扰 2021-02-04 04:06

I have Realm Object that save list from the JSON Response. But now i need to remove the object if the object is not on the list again from JSON. How i do that? This is my init f

6条回答
  •  长情又很酷
    2021-02-04 04:51

    imagine your Items object has an id property, and you want to remove the old values not included in the new set, either you could delete everything with just

    let result = realm.objects(Items.self)
    realm.delete(result)
    

    and then add all items again to the realm, or you could also query every item not included in the new set

    let items = [Items]() // fill in your items values
    // then just grab the ids of the items with
    let ids = items.map { $0.id }
    
    // query all objects where the id in not included
    let objectsToDelete = realm.objects(Items.self).filter("NOT id IN %@", ids)
    
    // and then just remove the set with
    realm.delete(objectsToDelete)
    

提交回复
热议问题