Search code examples
iosswiftcore-data

Delete all data from an attribute in CoreData


How to delete all data for example from an attribute <name>, not Entity, from attribute. I have an entity name - Users, attribute - name and I don't know how to delete all data from an attribute.


Solution

  • for delete the all data you can use this function

    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)
                print("Deleted")
            }
    
        } catch let error as NSError {
            print(error)
        }
    }
    

    and after that call the function like this

    deleteAllData(entity: "your Entity name")