swift ios - 如何从AppDelegate

时间:2017-05-07 12:41:15

标签: ios swift function appdelegate func

我正在尝试使用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

var money: Double = 0.000

我错过了什么?

谢谢!

1 个答案:

答案 0 :(得分:9)

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

最好的选择是收听iOS提供的UIApplicationDidBecomeActive通知。

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

确保您也删除了观察者,这通常是在deinit方法

中完成的
deinit() {
    NotificationCenter.default.removeObserver(self)
}