iOS: Delete ALL Core Data Swift

前端 未结 23 739
爱一瞬间的悲伤
爱一瞬间的悲伤 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:43

    You can use destroyPersistentStore starting in iOS 9.0 and Swift 3:

    public func clearDatabase() {
        guard let url = persistentContainer.persistentStoreDescriptions.first?.url else { return }
    
        let persistentStoreCoordinator = persistentContainer.persistentStoreCoordinator
    
         do {
             try persistentStoreCoordinator.destroyPersistentStore(at:url!, ofType: NSSQLiteStoreType, options: nil)
             try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url!, options: nil)
        } catch let error {
             print("Attempted to clear persistent store: " + error.localizedDescription)
            }
        }
    }
    

提交回复
热议问题