我想通过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)
}
非常感谢您的协助。
我仍然遇到错误,不知道为什么。
无法识别的选择器发送到实例
这就是我的代码的样子。怎么了?
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)
}
答案 0 :(得分:8)
您不能使用NSTimer传递多个参数,但是,您可以将该参数设置为数组或ditionary或类似参数。
然后创建一个新函数,该函数接受该数组/字典,然后使用数组/字典中的每个参数调用函数
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...
}