小编典典

swift iOS-如何从AppDelegate在ViewController中运行功能

swift

我正在尝试ViewController使用某些功能AppDelegate

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

我错过了什么?

谢谢!


阅读 502

收藏
2020-07-07

共1个答案

小编典典

ViewController().grabData()将创建ViewController的新实例并调用此函数。然后,由于不使用视图控制器,它将被垃圾回收/从内存中删除。您需要在使用中的实际视图控制器上调用此方法。不是它的新实例。

最好的选择是监听UIApplicationDidBecomeActiveiOS提供的通知。

NotificationCenter.default.addObserver(
    self,
    selector: #selector(grabData),
    name: NSNotification.Name.UIApplicationDidBecomeActive,
    object: nil)

确保您也删除了观察者,这通常是通过一种deinit方法完成的

deinit() {
    NotificationCenter.default.removeObserver(self)
}
2020-07-07