Passing parameters to a method called by NSTimer in Swift

后端 未结 2 1304
梦谈多话
梦谈多话 2020-11-29 13:00

I\'m trying to pass an argument to a method that is called by NSTimer in my code. It is throwing an exception. This is how I\'m doing it. Circle is my custom class.

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 13:29

    Your selector needs to be a string unless that's supposed to be an ivar. Also, your animate function has the wrong signature. The following changes should get you moving again:

    var circle = Circle()
    var timer = NSTimer.scheduledTimerWithInterval(1.0, target: self, selector: "animate", userInfo: circle, repeats: true)
    
    func animate(circle: Circle) -> () {
      //do stuff with circle
    }
    

    The function really doesn't need to return the empty tuple; it can be written without the -> ()

    I've also seen the selector string wrapped in a "Selector()" method: Selector("animate"). It works either way.

    I've been messing with NSTimer and closures myself and wrote an article on it: Using Swift's Closures With NSTimer

提交回复
热议问题