gpt4 book ai didi

ios - 我想从 CoreData 获取数据,如果数据存在我想返回 true,如果不存在我想返回 false

转载 作者:行者123 更新时间:2023-11-28 23:22:51 25 4
gpt4 key购买 nike

我想从 CoreData 获取数据,如果数据存在我想返回 true,如果不存在我想返回 false,我正在处理 Favoris,所以我想获取事件 ID 是否存在于 CoreData 中,如果我是否想返回 true,如果不是,它将返回 false,这是我的代码:

    func  retrieveFavoris() {

//As we know that container is set up in the AppDelegates so we need to refer that container.
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }

//We need to create a context from this container
let managedContext = appDelegate.persistentContainer.viewContext

//Prepare the request of type NSFetchRequest for the entity
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Favoris")


do {
let result = try managedContext.fetch(fetchRequest)
for data in result as! [NSManagedObject] {
print(data.value(forKey: "id_event") as! String)
}

} catch {

print("No Favoris")
}
}

PS:我的 xcdata 文件包含一个实体“Favoris”,它只包含一个属性“id_event”

我想测试 id 事件是否存在于 CoreData 中,所以我想我必须传入一个我输入的 event_id 参数,然后测试它是否存在,所以函数应该返回一个 bool 值 true 如果存在,如果存在则返回 false不存在。

有什么帮助吗?谢谢

最佳答案

您必须为 id 事件添加参数、返回类型和谓词。

func retrieveFavoris(idEvent: Int) -> Bool {

//As we know that container is set up in the AppDelegates so we need to refer that container.
let appDelegate = UIApplication.shared.delegate as! AppDelegate

//We need to create a context from this container
let managedContext = appDelegate.persistentContainer.viewContext

//Prepare the request of type NSFetchRequest for the entity
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Favoris")
fetchRequest.predicate = NSPredicate(format: "id_event = %ld", idEvent)
do {
return try !managedContext.fetch(fetchRequest).isEmpty
} catch {
print("No Favoris", error)
return false
}
}

关于ios - 我想从 CoreData 获取数据,如果数据存在我想返回 true,如果不存在我想返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59374793/

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