Swift - 计时器#selector 不适用于其他控制器方法

Swift - Timer #selector doesn't work with other controller method

我尝试使用 Timer #selector 从 AppDelegate 中的 MainViewController 访问一个方法。但它给我一个错误:"unrecognized selector sent to instance"

在我的 AppDelegate 中,我有一个计时器;

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        MainViewController().test() //this line prints successful!

        _ = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(MainViewController.test), userInfo: nil, repeats: true)

}

在我的 MainViewController 中;

func test() {
   print("successful!")
}

当我将该功能移动到 AppDelegate 时,它​​的工作方式为 #selector(self.test)

这是无法实现还是我错过了什么?

这可能是实现您的目标的便捷方式:

class AppDelegate : UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    let view = MainViewController()
    view.setupTimer()
}

class MainViewController: UIViewController {
var timer: Timer!
func test(sender: NSTimer!) {
    /* code */
}

func setupTimer() {
    timer = Timer.scheduledTimerWithTimeInterval(timeInterval: 5.0, target: controller, selector: #selector(test), userInfo: nil, repeats: true)
}

试试这个,在你的 AppDelegate 中添加你的 MainViewController 作为 var,然后你可以将它用作你的 scheduledTimer 的目标,并且作为 #selector 你必须通过test

var controller = MainViewController()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    _ = Timer.scheduledTimer(timeInterval: 5.0, target: controller, selector: #selector(ViewController.test), userInfo: nil, repeats: true)

    return true
}

我希望这对你有帮助,它有效

目标是本身必须具有方法的目标,在这种情况下,应用程序委托没有方法 test 并且会崩溃。通过围绕以下行做一些事情它会正常工作:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        let mainVC = MainViewController()

        _ = Timer.scheduledTimer(timeInterval: 5.0, target: mainVC, selector: #selector(MainViewController.test), userInfo: nil, repeats: true)

}

这样做,就是告诉定时器它必须调用的选择器在 MainViewController 的那个特定实例中