我尝试使用Timer #selector从AppDelegate中的MainViewController访问一个方法。但它给了我一个错误:"无法识别的选择器被发送到实例"
在我的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)
难道难以置信,还是我错过了什么?
答案 0 :(得分:2)
试试这个,将MainViewController
添加为AppDelegate
中的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
}
1}}
npm i dexie@next --save
我希望这可以帮到你,它有效
答案 1 :(得分:0)
这可能是实现目标的便捷方式:
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)
}
答案 2 :(得分:0)
目标是必须拥有方法本身的目标,在这种情况下,app委托没有方法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的特定实例中