iOS: Delete ALL Core Data Swift

前端 未结 23 675
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 11:20

I am a little confused as to how to delete all core data in swift. I have created a button with an IBAction linked. On the click of the button I have the follow

23条回答
  •  离开以前
    2020-12-04 11:51

    Here is my implementation to clear all core data in Swift 3, based on Jayant Dash's excellent (and comprehensive) answer. This is simpler due to only supporting iOS10+. It deletes all core data entities, without having to hardcode them.

    public func clearAllCoreData() {
        let entities = self.persistentContainer.managedObjectModel.entities
        entities.flatMap({ $0.name }).forEach(clearDeepObjectEntity)
    }
    
    private func clearDeepObjectEntity(_ entity: String) {
        let context = self.persistentContainer.viewContext
    
        let deleteFetch = NSFetchRequest(entityName: entity)
        let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
    
        do {
            try context.execute(deleteRequest)
            try context.save()
        } catch {
            print ("There was an error")
        }
    }
    

提交回复
热议问题