问题
Scene support and multiple windows in iOS 13 have complicated the question of when to save data. A scene delegate's sceneDidEnterBackground
might seem like a pretty good place, but there are times when it won't be sufficient:
If your scene was frontmost and the user goes to the app switcher and terminates your app, you'll get
sceneDidDisconnect
andapplicationWillTerminate
, notsceneDidEnterBackground
.If the user switches off the device while your app is frontmost, you'll get
applicationWillTerminate
, notsceneDidEnterBackground
.
What strategy are people using to manage data saving in iOS 13 apps that support window scenes and possibly multiple windows?
回答1:
From the docs for UISceneDelegate.sceneWillResignActive(_:):
If your scene has unsaved user data, save that data here to ensure that it isn't lost. However, never save data solely from this method. Instead, save it at appropriate points from your view controllers, usually in response to user actions. For example, save data when the user dismisses a data-entry screen. Do not rely on specific app transitions to save all of your app's critical data.
They also state in the docs for UISceneDelegate.sceneDidDisconnect(_:):
Use this method to perform any final cleanup before your scene is purged from memory. For example, use it to release references to files or shared resources and to save user data.
So it looks like Apple recommends that we save user data as events happen, like in response to the user doing something (dismissing a view controller, toggling a switch, entering text into a text field, etc.), but we may use sceneWillResignActive(_:)
and/or sceneDidDisconnect(_:)
to save some data if we need or want to.
来源:https://stackoverflow.com/questions/58567287/in-ios-13-when-to-save-data