Dim San Cing Dim San Cing - 7 months ago 52
Swift Question

how to override data in core data ? how to solve duplicate data in Core Data?

I am fetching data from a server and then I save all of the data to Core Data.
But when I save it, it creates multiple copies(duplicate data).

My questions are :


  1. How to handle duplicate data in Core Data?

  2. How to save override data using Swift in CoreData?


Answer

To save new data in core data, you can delete all records from the core data and then you can save all record in core data.

Here is function to delete all record from core data. you can call this function before saving records in core data.

 func deleteEverything()
 {
    let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
    let context = appDel.managedObjectContext
    let coord = appDel.persistentStoreCoordinator

    let fetchRequest = NSFetchRequest(entityName: "Categorytbl") // Your entity name
    if #available(iOS 9.0, *)
    {
        let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
        do
        {
            try coord.executeRequest(deleteRequest, withContext: context)
        }
        catch let error as NSError
        {
            debugPrint(error)
        }
    }
    else
    {
        // Fallback on earlier versions
        do{
            let fetchedObjects : NSArray = try context.executeFetchRequest(fetchRequest)
            if(fetchedObjects.count > 0)
            {
                for currObj in fetchedObjects
                {
                    context.deleteObject(currObj as! NSManagedObject)
                }
                let _ : NSError! = nil
                do {
                    try context.save()
                } catch {
                    print("Error in Deletion : \(error)")
                }
            }
        }
        catch let error as NSError
        {
            debugPrint(error)
        }
    }
}

I had a same issue. Its working fine at my end.