菜鸟教程小白 发表于 2022-12-11 22:27:02

ios - 为什么快速重新启动应用程序时会清除核心数据?


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

<p><strong>saveContext 方法 - :</strong></p>

<pre><code>func saveContext () -&gt; 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(&#34;Unresolved error \(nserror), \(nserror.userInfo)&#34;)
            }
      }
      return saveFlag
    }
</code></pre>

<p><strong>注意:</strong> 从上面的 saveContext() 方法中,不进入 context.hasChanges 条件。因此,不要打印错误消息。它超出了条件并返回 <strong>saveFlag</strong> 作为 <strong>false。</strong> </p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p><code>var appDel:AppDelegate = UIApplication.shared.delegate as! AppDelegate</code></p>

<pre><code>      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(&#34;Unresolved error \(nserror), \(nserror.userInfo)&#34;)
            }
      }
      return saveFlag
    }```

Please try the above code
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 为什么快速重新启动应用程序时会清除核心数据?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/55135418/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/55135418/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 为什么快速重新启动应用程序时会清除核心数据?