Swift 4中如何在App Delegate调用ViewController方法?Xcode报错求助
解决Swift 4中AppDelegate调用ViewController方法的报错问题
嘿,这个报错我太熟了!你遇到的核心问题是:pauseGame322是ViewController的实例方法,但你却直接用类名ViewController.去调用它——这就好比你想让“人类”这个群体去做某件只有具体某个人才能完成的事,Xcode当然会报错啦。
我给你几个实用的解决办法,按需选择就行:
方法一:获取当前显示的ViewController实例
如果你需要调用的是当前正在显示的那个ViewController的方法,可以先写个工具方法定位到它:
func getCurrentViewController() -> UIViewController? { guard let window = UIApplication.shared.keyWindow else { return nil } var currentViewController = window.rootViewController // 遍历找到最上层的弹窗控制器 while let presentedVC = currentViewController?.presentedViewController { currentViewController = presentedVC } // 转成你的ViewController类型 return currentViewController as? ViewController }
然后在applicationWillTerminate里这样调用:
func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. if let currentVC = getCurrentViewController() { currentVC.pauseGame322() // 注意:你原来代码里传的ViewController参数是错误的,直接调用方法即可(如果方法不需要参数的话) } }
方法二:把方法改成类方法(如果逻辑允许)
如果pauseGame322方法不需要访问ViewController的实例属性(比如不需要操作界面控件、实例变量),那可以直接把它改成类方法:
在ViewController里修改方法定义:
class ViewController: UIViewController { // 用class修饰,将实例方法转为类方法 class func pauseGame322() { // 你的方法逻辑 } }
然后在AppDelegate里就能直接调用了:
func applicationWillTerminate(_ application: UIApplication) { ViewController.pauseGame322() }
方法三:用通知中心解耦(推荐低耦合场景)
这种方法不需要直接获取ViewController实例,耦合度更低,适合大多数场景:
- 在ViewController里注册通知:
override func viewDidLoad() { super.viewDidLoad() // 注册监听"应用即将终止"的通知 NotificationCenter.default.addObserver(self, selector: #selector(pauseGame322), name: NSNotification.Name(rawValue: "AppWillTerminateNotification"), object: nil) } // 记得在控制器销毁时移除观察者,避免内存泄漏 deinit { NotificationCenter.default.removeObserver(self) } // 确保方法被@objc修饰,不然通知无法识别它 @objc func pauseGame322() { // 你的方法逻辑 }
- 在AppDelegate里发送通知:
func applicationWillTerminate(_ application: UIApplication) { // 发送通知,触发ViewController里的pauseGame322方法 NotificationCenter.default.post(name: NSNotification.Name(rawValue: "AppWillTerminateNotification"), object: nil) }
内容的提问来源于stack exchange,提问作者Andrew Dogg
相关产品推荐
相关产品推荐

