Delete/Reset all entries in Core Data?

后端 未结 30 2785
天命终不由人
天命终不由人 2020-11-22 16:00

Do you know of any way to delete all of the entries stored in Core Data? My schema should stay the same; I just want to reset it to blank.


Edit

30条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 16:22

    Updated Solution for iOS 10+

    Use NSBatchDeleteRequest to delete all objects in the entity without having to load them into memory or iterate through them.

    // create the delete request for the specified entity
    let fetchRequest: NSFetchRequest = MyEntity.fetchRequest()
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
    
    // get reference to the persistent container
    let persistentContainer = (UIApplication.shared.delegate as! AppDelegate).persistentContainer
    
    // perform the delete
    do {
        try persistentContainer.viewContext.execute(deleteRequest)
    } catch let error as NSError {
        print(error)
    }
    

    This code has been updated for iOS 10 and Swift 3. If you need to support iOS 9, see this question.

    Sources:

    • Core Data: Quickest way to delete all instances of an entity (includes Objective-C code)
    • What's New in Core Data (WWDC 2015 video)
    • What's New in Core Data (WWDC 2016 video)
    • How to Use Core Data in iOS 10
    • What’s new in Core Data Swift 3.0

提交回复
热议问题