如何删除CoreData Swift 3中的所有实体对象

时间:2016-12-09 11:18:09

标签: swift xcode core-data swift3 xcode8

所以我有这个代码工作正常,但我想要一个更好的。

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()

}

目前我通过for循环逐个删除对象。

3 个答案:

答案 0 :(得分:0)

你可以试试这个:

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)")
    }
}

用法:

self.deleteAllData("your_entityName")

已在https://stackoverflow.com/a/33931528/2894160

中看到

答案 1 :(得分:0)

最好删除持久性存储,然后添加新的存储,而不是循环每个实体(如果要从coredata中删除所有实体)。

func deletePersistentStoreCoordinator(){

myRecyclerAdapter.addNewDataset(data);

答案 2 :(得分:-1)

以下是从Core Data中删除记录的代码: //从本地数据库中删除用户信息

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 {}
    }
}