gpt4 book ai didi

快速从 Realm 中删除对象

转载 作者:IT王子 更新时间:2023-10-29 05:28:25 25 4
gpt4 key购买 nike

我有从 JSON 响应中保存列表的 Realm 对象。但是现在如果对象不在 JSON 的列表中,我需要删除该对象。我该怎么做?这是我的 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 属性,您想要删除未包含在新集合中的旧值,或者您可以只删除所有内容

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

然后再次将所有项目添加到 Realm ,或者您也可以查询未包含在新集合中的每个项目

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)

关于快速从 Realm 中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40970582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com