Passing parameters to the method called by a NSTimer

前端 未结 6 1101
我寻月下人不归
我寻月下人不归 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:52

    For Swift 4.0:

    You can have a function with any parameters you want and use the "scheduledTimer" block to execute the code you need to repeat.

    func someFunction(param1: Int, param2: String) {
    
        let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
            print(param1)
            print(param2)
        }
    }
    

    Be careful to call timer.invalidate() when you finish to prevent it from running continuously.

提交回复
热议问题