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

标签 ios swift core-data

我想从 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/

相关文章:

ios - 无法分享到 Facebook 的链接

ios - WatchKit openParentApplication :reply

ios - UIViewController 内的 UITableView 不显示

swift - 如何在 OS X 的桌面 View 底部创建 +/- 按钮?

ios - 旋转后的 CollectionView 布局

ios - 如何检查核心数据中是否存在对象

ios - 核心数据 : Segue to detail controller with newly created ManagedObject

android - 适用于手机的 Google Maps API 夜间主题

swift - 为函数的参数分配默认值的困难

ios - 从 `TableViewCell` 触发 `ViewWillAppear` 函数