ios - swift ios - 如何从 AppDelegate 在 ViewController 中运行函数

标签 ios swift function appdelegate func

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

相关文章:

ios - Swift:添加到新 View 时,图像不会出现在 ImageView 中

c - 这个 C 编译器错误是什么意思?

swift - 函数返回空值

ios - 按嵌套对象中的字符串过滤 NSArray

ios - UIAlertController swift

iphone - 在不重新加载的情况下更新 UITableView 中的部分页脚标题

ios - UITableViewCell 延迟实例化中的 `self.bounds.size.width`

javascript - 通过函数返回值仍然存在问题

iOS 键盘键移出屏幕顶部

ios - iOS 中的 iswalpha() 在 iOS 上返回的值与在 MacOS 上返回的值不同