1

So I have this code which works fine, but I want a much better one.

func deleteCoreDataObjects() {
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    //where groupData is an Array of an Entity
    for i in 0..<self.groupData.count {
        context.delete(groupData[i])
    }


    (UIApplication.shared.delegate as! AppDelegate).saveContext()

}

Currently I'm deleting the objects one by one via for loop.

Chris Mikkelsen
  • 3,987
  • 9
  • 29
  • 41

3 Answers3

0

You can try this:

func deleteAllData(entity: String)
{
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext
    let fetchRequest = NSFetchRequest(entityName: entity)
    fetchRequest.returnsObjectsAsFaults = false

    do 
    {
        let results = try managedContext.executeFetchRequest(fetchRequest)
        for managedObject in results
        {
            let managedObjectData:NSManagedObject = managedObject as! NSManagedObject
            managedContext.deleteObject(managedObjectData)
        }
    } catch let error as NSError {
        print("Detele all data in \(entity) error : \(error) \(error.userInfo)")
    }
}

Usage:

self.deleteAllData("your_entityName")

Already seen in: https://stackoverflow.com/a/33931528/2894160

Community
  • 1
  • 1
Jimmy James
  • 825
  • 12
  • 28
0

Best is delete the persistence storage and then add new one instead of looping each entity (if you want to delete all entities from coredata).

func deletePersistentStoreCoordinator () {

    do {
        let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("YourDatabaseName.sqlite")
        try self.persistentStoreCoordinator.destroyPersistentStoreAtURL(url, withType: NSSQLiteStoreType, options: nil)
        try self.persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
    }
    catch{

    }
}
Anoop Rawat
  • 357
  • 4
  • 9
-1

Here is the code for deleting records from Core Data : //Delete user info from local db

func deleteUserInfo()  {

    let context = appdelegate.managedObjectContext
    let coord   = appdelegate.persistentStoreCoordinator

    let fetchRequest = NSFetchRequest(entityName: "User")
    if #available(iOS 9.0, *) {
        let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
        //let predicate = NSPredicate(format: "id == %@", key)
        //fetchRequest.predicate = predicate
        do {
            try coord.executeRequest(deleteRequest, withContext: context)
        }
        catch let error as NSError {
            //Error handling
        }
        catch {}
    } else {
        // Fallback on earlier versions

        do {
        let users: NSArray = try appdelegate.managedObjectContext.executeFetchRequest(fetchRequest)

        for user in users {
            appdelegate.managedObjectContext.delete(user)
        }

        try appdelegate.managedObjectContext.save()

        } catch let error as NSError {
            //Error handling
        }
        catch {}
    }
}
Shobhakar Tiwari
  • 7,862
  • 4
  • 36
  • 71