我正在尝试使用 AppDelegate
在某些 ViewController
中运行一个函数
func applicationDidBecomeActive(_ application: UIApplication) {
ViewController().grabData()
}
但不知何故,当应用程序从后台进入应用程序后变为事件状态时,该功能似乎根本没有运行。
函数看起来像这样
func grabData() {
self._DATASERVICE_GET_STATS(completion: { (int) -> () in
if int == 0 {
print("Nothing")
} else {
print(int)
for (_, data) in self.userDataArray.enumerated() {
let number = Double(data["wage"]!)
let x = number!/3600
let z = Double(x * Double(int))
self.money += z
let y = Double(round(1000*self.money)/1000)
self.checkInButtonLabel.text = "\(y) KR"
}
self.startCounting()
self.workingStatus = 1
}
})
}
并使用这个变量
var money: Double = 0.000
我错过了什么?
谢谢!
最佳答案
ViewController().grabData()
将创建一个新的 ViewController 实例并调用此函数。然后.. 由于 View Controller 未在使用中,它将被垃圾收集/从内存中删除。您需要在正在使用的实际 View Controller 上调用此方法。不是它的新实例。
最好的选择是监听 iOS 提供的 UIApplicationDidBecomeActive
通知。
NotificationCenter.default.addObserver(
self,
selector: #selector(grabData),
name: NSNotification.Name.UIApplicationDidBecomeActive,
object: nil)
确保你也删除了观察者,这通常在 deinit
方法中完成
deinit() {
NotificationCenter.default.removeObserver(self)
}
关于ios - swift ios - 如何从 AppDelegate 在 ViewController 中运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43831571/