快速从领域删除对象 [英] Swift Remove Object from Realm

查看:58
本文介绍了快速从领域删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Realm对象,该对象保存了JSON响应中的列表.但是现在,如果该对象不在JSON列表中,那么我现在需要删除该对象.我该怎么做? 这是我的境界初始化

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>
}

推荐答案

想象您的Items对象具有id属性,并且您想删除新集合中未包含的旧值,或者可以删除所有内容,而只需删除

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)

这篇关于快速从领域删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆