NSTimer 选择器中的多个参数

Multiple parameters in NSTimer selector

我想通过userInfo向下面的函数传递参数,因为那个函数必须延迟执行。

func showAlert(alertTitle: String, withMessage alertMessage: String, fromController controller: UIViewController) {
     //do stuff...
}

这部分已经延迟完成,但我不知道如何将多个参数发送到 showAlert.

的正文
func fireTimer() {
   timer = NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: Selector("showAlert:"), userInfo: nil, repeats: false)
}

非常感谢您的帮助。


我仍然遇到错误,不知道为什么。

unrecognized selector sent to instance

这就是我的代码的样子。怎么了?

class AlertController: UIAlertController {  
var timer = NSTimer()

func showAlert(alertTitle: String, withMessage alertMessage: String, fromController controller: UIViewController)
{
    var alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .Alert)
    controller.presentViewController(alert, animated: true, completion: nil)
}

func showAlert2(dict: [String: AnyObject])
{
    showAlert(dict["title"] as! String,
        withMessage: dict["message"] as! String,
        fromController: dict["controller"] as! UIViewController)
}

func fireTimer(title: String, message: String, viewController: UIViewController)
{
    timer = NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: Selector("showAlert2:"), userInfo: ["title":title, "message": message, "controller": viewController], repeats: false)
}

您不能使用 NSTimer 传递一个以上的参数,但是,您可以将该参数放入一个数组或二元数组或类似的数组中。

然后创建一个接受该 array/dictionary 的新函数,然后使用 array/dictionary

中的每个参数调用您的函数
func fireTimer() {
    timer = NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: Selector("showAlert2:"), userInfo: ["title":"a title", "message": "a message", "controller": controller], repeats: false)
}

func showAlert2(timer: NSTimer) {   
    let dict = timer.userInfo as NSDictionary

    showAlert(dict["title"] as String, wwithMessage: dict["message"] as String, fromController: dict["controller"] as UIViewController)
}

func showAlert(alertTitle: String, withMessage alertMessage: String, fromController controller: UIViewController) {
//    do stuff...
}