OGeek|极客世界-中国程序员成长平台

标题: ios - 为什么快速重新启动应用程序时会清除核心数据? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 22:27
标题: ios - 为什么快速重新启动应用程序时会清除核心数据?

我使用核心数据作为本地数据库来将本地数据保存在我的 iOS 应用程序中。当应用程序终止并再次重新启动时,本地数据将从核心数据中清除。我从 applicationDidEnterBackgroundapplicationWillTerminate 方法调用 saveContext()。一件事是我更改了核心数据版本。此更改将对重新启动应用程序后的清除数据产生任何影响。

saveContext 方法 - :

func saveContext () -> Bool {
        let context = persistentContainer.viewContext
        var saveFlag = false
        if context.hasChanges {
            do {
                try context.save()
                saveFlag = true
            } catch {
                saveFlag = false
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
        return saveFlag
    }

注意: 从上面的 saveContext() 方法中,不进入 context.hasChanges 条件。因此,不要打印错误消息。它超出了条件并返回 saveFlag 作为 false。



Best Answer-推荐答案


var appDel:AppDelegate = UIApplication.shared.delegate as! AppDelegate

        let context = appDel.persistentContainer.viewContext
        var saveFlag = false
        if context.hasChanges {
            do {
                try context.save()
                saveFlag = true
            } catch {
                saveFlag = false
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
        return saveFlag
    }```

Please try the above code

关于ios - 为什么快速重新启动应用程序时会清除核心数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55135418/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4