swift ios – 如何从AppDelegate在ViewController中运行函数
发布时间:2020-12-14 05:44:15 所属栏目:百科 来源:网络整理
导读:我试图使用AppDelegate在某些ViewController中运行一个函数 func applicationDidBecomeActive(_ application: UIApplication) { ViewController().grabData()} 但不知何故,当应用程序从后台进入应用程序后变为活动状态时,该功能似乎根本无法运行. 该功能看起
我试图使用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 var money: Double = 0.000 我错过了什么? 谢谢!
ViewController().grabData()将创建一个ViewController的新实例并调用此函数.然后..由于视图控制器未被使用,它将被垃圾收集/从内存中删除.您需要在正在使用的实际视图控制器上调用此方法.不是它的新实例.
最好的选择是监听iOS提供的UIApplicationDidBecomeActive通知. NotificationCenter.default.addObserver( self,selector: #selector(grabData),name: NSNotification.Name.UIApplicationDidBecomeActive,object: nil) 确保你也删除了观察者,这通常是以deinit方法完成的 deinit() { NotificationCenter.default.removeObserver(self) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |