Bartek
Bartek

Reputation: 29

Checking if entity exist before saving it to core data swift4.

I'm trying to add data to Core Data in my application. When I save it without checking if it already exists it works fine. But I don't what duplicates in my core data so what I do I fetch all the entities with the name of entity im trying to add first and then check if it's 0 I add it else no. But I'm keep getting an error when trying to save. If anyone could help me with the problem.

This is my checking function:

func entityExists(name: String) -> Bool {
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "name")
    fetchRequest.includesSubentities = false

    var entitiesCount = 0

    do {
        entitiesCount = try coreDataController.mainContext.count(for:         fetchRequest)
    }
    catch {
        print("error executing fetch request: \(error)")
    }

    if entitiesCount == 0{
        return true
    } else {
        return false
    }
}

This is my code when I save the data.

if entityExists(name: (scrimmagePassedOver?.name)!) == true{

    coreDataController.saveContext()
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "load"), object: nil)

    let alert = UIAlertController(title: "Saved!", message: "You have saved your Scrimmage.", preferredStyle: UIAlertControllerStyle.alert)

   // add an action (button)
    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
    self.present(alert, animated: true, completion: nil)
   } else {
    let alert = UIAlertController(title: "hey", message: "You have saved this Scrimmage before.", preferredStyle: UIAlertControllerStyle.alert)
   alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
   self.present(alert, animated: true, completion: nil)
    }

Upvotes: 2

Views: 3955

Answers (1)

Shabbir Ahmad
Shabbir Ahmad

Reputation: 615

You can check the record from your core data like that:

func checkRecordExists(entity: String,uniqueIdentity: String,idAttributeName:String) -> Bool {
    let context = getManagedObjectContext()
    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entity)
    fetchRequest.predicate = NSPredicate(format: "\(idAttributeName) CONTAINS[cd] %@", createdDate)

    var results: [NSManagedObject] = []

    do {
        results = try context.fetch(fetchRequest)
    }
    catch {
        print("error executing fetch request: \(error)")
    }

    return results.count > 0

}

and managedObjectContext is:

func getManagedObjectContext() -> NSManagedObjectContext{

    let delegate = UIApplication.shared.delegate as? AppDelegate

    return delegate!.persistentContainer.viewContext
} 

If you get false then save it.

Upvotes: 2

Related Questions