作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想从 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/
我有 json 数据: { "products": [ { "productId" : 0, "productImg" : "../img/product-ph
我是一名优秀的程序员,十分优秀!