gpt4 book ai didi

swift - NSTimer 选择器中的多个参数

转载 作者:可可西里 更新时间:2023-10-31 23:59:20 26 4
gpt4 key购买 nike

我想通过 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 传递多个参数,但是,您可以将该参数放入一个数组或双数或类似的。

然后创建一个接受该数组/字典的新函数,然后使用数组/字典中的每个参数调用您的函数

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...
}

关于swift - NSTimer 选择器中的多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29267105/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com