I am new in Swift and I want to delete all data from core data. I have seen several examples but in all of them persistentContainer
is in AppDelegate
and in my case persistentContainer
is not in AppDelegate
. It is in a different class as shown below:
class CoreDataStack: NSObject {
static let sharedInstance = CoreDataStack()
private override init() {}
func applicationDocumentsDirectory() {
if let url = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).last {
print(url.absoluteString)
}
}
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "Database")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
print(storeDescription)
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
In the AppDelegate method I am just calling it as
CoreDataStack.sharedInstance.applicationDocumentsDirectory()
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
CoreDataStack.sharedInstance.saveContext()
}
I tried this code but it does not work for me.