Passing parameters to the method called by a NSTimer

前端 未结 6 1073
我寻月下人不归
我寻月下人不归 2020-12-02 09:08

How can I pass a parameter to the method called by a NSTimer? My timer looks like this:

[NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selec         


        
6条回答
  •  离开以前
    2020-12-02 09:35

    Additional example in Swift using Dictionary literal for passing parameters to the method called by NSTimer:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        let dictionary: [String : AnyObject] = ["first element" : "Jordan",
                                                "second element" : Int(23)]
    
        NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(0.41),
                                               target: self,
                                               selector: "foo:",
                                               userInfo: dictionary,
                                               repeats: false)
    }
    
    func foo(timer: NSTimer) {
            let dictionary: [String : AnyObject] = timer.userInfo! as! [String : AnyObject]
            let firstElement: String = dictionary["first element"] as! String
            let secondElement: Int = dictionary["second element"] as! Int
            print("\(firstElement) - \(secondElement)")
    }
    

提交回复
热议问题