Core Data deleted when I changed the container destination

104 views Asked by At

I had been using core data for a long time in my app, with the standard setup, but when I changed the NSPersistentContainer, everything was deleted. I expected that the new NSPersistentContainer would be empty, but then when I went back to the original NSPersistentContainer there was now nothing in there either (beforehand over 10,000 objects)

Original standard setup

lazy var persistentContainer: NSPersistentContainer = {

    let container = NSPersistentContainer(name: "MyApp")

    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {

            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

But when I changed the Persistent container to share the app data with an extension using the following code, the app data all seemingly disappeared.

lazy var persistentContainer: NSPersistentContainer = {

    let container = NSCustomPersistentContainer(name: "MyApp")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {

            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

class NSCustomPersistentContainer: NSPersistentContainer {

    override open class func defaultDirectoryURL() -> URL {
        var storeURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.MyApp")
        storeURL = storeURL?.appendingPathComponent("MyApp.sqlite")
        return storeURL!
    }

}

When I went back to using the previous setup - i.e.

let container = NSPersistentContainer(name: "MyApp")

instead of

let container = NSCustomPersistentContainer(name: "MyApp")

there is no data returned from the database. Is it possible that changing the location of the persistent container could really delete all the data in the original container. I presumed it would create two separate containers, and so I could just switch back to the original one and everything would still be there.

0

There are 0 answers