Reputation: 41
I want to fetch data from CoreData and if the data exist I want to return true, if not I want to return false, I'm working on Favoris, so I want to fetch if the event id exists in CoreData, if it does i want to return true and if not it will return false, there is my code:
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: my xcdata file contains one Entity "Favoris" which contains only one attribute "id_event"
I want to test if id event exists in CoreData, so i think i have to pass in parameters an event_id that i enter and then test if it exist, so the function should return a boolean value true if exist and false if does not exist.
Any help please? Thank you
Upvotes: 0
Views: 81
Reputation: 2206
If you want to check only data is exists or not then use result.count
:
func retrieveFavoris() -> Bool {
//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")
let predicate = NSPredicate(format: "id_event = %@", id_event_value)
fetchRequest.predicate = predicate
do {
let result = try managedContext.fetch(fetchRequest)
return (result.count > 0)
} catch {
print("No Favoris")
return false
}
}
Upvotes: 0
Reputation: 285079
You have to add a parameter, a return type and a predicate for the id event.
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
}
}
Upvotes: 1