Handling duplicate entries in Core Data

前端 未结 6 491
野的像风
野的像风 2021-02-04 10:28

I have an app that allows users to save favorites. I am using Core Data to store the favorites as managed objects. I have written some code to prevent the possibility of storing

6条回答
  •  悲&欢浪女
    2021-02-04 10:44

    Swift 4 Curled from @Vahid answer

    func isEntityAttributeExist(id: Int, entityName: String) -> Bool {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let managedContext = appDelegate.persistentContainer.viewContext
        let fetchRequest = NSFetchRequest(entityName: entityName)
        fetchRequest.predicate = NSPredicate(format: "id == %@", id)
        let res = try! managedContext.fetch(fetchRequest)
        return res.count > 0 ? true : false
    }
    

提交回复
热议问题