我有一个在 viewController 中更新了属性的类。我想在应用程序进入后台或使用 AppDelegate 退出时保存属性。我使用了以下代码,但似乎没有将属性传递给 AppDelegate。此外,applicationWillTerminate 代码似乎没有得到执行。
// testClass is defined and the properties are updated in viewController, e.g
testClass.status = true // default is false
// I want to save testClass.status when the app goes into background or being terminated using the following:
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var vc = ViewController()
func applicationDidEnterBackground(_ application: UIApplication) {
print(vc.testClass.status) // prints false
//codes to save
}
// save before App is terminated
func applicationWillTerminate(_ application: UIApplication) {
print(vc.testClass.status) // this code did not get executed?
//codes to save
}
}
最佳答案
applicationWillTerminate
仅在用户终止应用程序而不将其切换到后台模式时调用。
当应用程序处于事件状态时,双击主屏幕按钮并终止应用程序。
但如果您将应用程序切换到后台,然后尝试终止该应用程序,则不会调用 applicationWillTerminate
。
并且您正在 AppDelegate
中创建 ViewController
的实例
var vc = ViewController()
如果您更改另一个 ViewController
类实例中的 testClass 属性,您将不会在此处获得该值。所以像这样创建一个单例
类
class TestClass: NSObject {
static let shared = TestClass()
private override init() {
super.init()
}
var status = false
}
现在从单例类更新任何 View Controller 中的值
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
TestClass.shared.status = true
}
}
在 AppDelegate
中保存并从 UserDefaults
中检索值
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
TestClass.shared.status = UserDefaults.standard.bool(forKey: "Status")
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
UserDefaults.standard.set(TestClass.shared.status, forKey: "Status")
}
func applicationWillTerminate(_ application: UIApplication) {
UserDefaults.standard.set(TestClass.shared.status, forKey: "Status")
}
}
或者创建一个计算属性,以便在更改时将值保存在 UserDefaults 中。
class TestClass: NSObject {
static let shared = TestClass()
private override init() {
super.init()
}
var status: Bool {
get {
return UserDefaults.standard.bool(forKey: "Status")
}
set {
UserDefaults.standard.set(newValue, forKey: "Status")
}
}
}
关于swift - 如何在 AppDelegate 和 ViewController 之间共享属性,并在 App 终止之前保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56095998/