gpt4 book ai didi

swift - 在 Swift 中终止应用程序时调用函数

转载 作者:搜寻专家 更新时间:2023-11-01 05:48:09 24 4
gpt4 key购买 nike

当我的应用程序被用户终止时,我如何调用 SKScene 类中的函数?

我需要修改一个值并在应用程序终止时将其保存到 NSUserDefauts。

最佳答案

您可以注册以在您的应用程序即将终止时接收通知。为此,通过

将观察者添加到默认通知中心

swift 5:

 NotificationCenter.default.addObserver(self, selector: #selector(saveData), name: UIApplication.willTerminateNotification, object: nil)

swift 3/4:

// Add this to didMoveToView in your SKScene subclass
NotificationCenter.default.addObserver(self, selector: #selector(saveData), name: NSNotification.Name.UIApplicationWillTerminate, object: nil)

将以下方法添加到您的 SKScene 子类中。该方法将在应用程序终止之前被调用。必须通过添加 @objc 将其“公开”给 Objective-C,以便通知程序可以使用 #selector()

@objc func saveData(notification:NSNotification) {
// Save your data here
print("Saving data...")
}

关于swift - 在 Swift 中终止应用程序时调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27010431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com