Swift Remove Object from Realm

Voyager picture Voyager · Dec 5, 2016 · Viewed 32.1k times · Source

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 for realm

func listItems (dic : Array<[String:AnyObject]>) -> Array<Items> {
        let items : NSMutableArray = NSMutableArray()
        let realm = try! Realm()
        for itemDic in dic {
            let item = Items.init(item: itemDic)
                try! realm.write {
                    realm.add(item, update: true)
                }
            items.addObject(item)
        }
        return NSArray(items) as! Array<Items>
}

Answer

fel1xw picture fel1xw · Dec 5, 2016

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)