Core Data on Rare Occasions Randomly Deletes Everything

125 views Asked by At

Very rarely (<1% of users), a user will inform me that they open my app, and all their data is gone. The problem I'm having is that I am unable to replicate the issue because it happens so rarely. I don't even know how to begin fixing this problem. It seems like this does not happen while a user is using the app. They seem to just open it one day and the data is no longer there.

On one occasion, a user was able to recover the data by turning off and on the iCloud switch for my app (in the phone settings). However, this did not work for another user.

I was reading that iOS may delete the cache when the storage is full. However, to my understanding, the default location for the container is in Application Support.

Here is my Core Data implementation in App Delegate:

lazy var persistentContainer: NSPersistentContainer = {
    let container = NSPersistentCloudKitContainer(name: "Bench")
    
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            print("Unresolved error \(error), \(error.userInfo)")
        }
    })
    
    container.viewContext.automaticallyMergesChangesFromParent = true
    
    return container
}()

func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            context.perform {
                do {
                    try context.save()
                } catch {
                    let nserror = error as NSError
                    print(nserror.localizedDescription)
                }
            }
        }
    }

I access it globally like this:

let ad = UIApplication.shared.delegate as! AppDelegate
let context = ad.persistentContainer.viewContext
0

There are 0 answers