【问题标题】:Passing parameters to a method called by NSTimer in Swift将参数传递给 NSTimer 在 Swift 中调用的方法
【发布时间】:2014-09-13 09:15:31
【问题描述】:

我正在尝试将参数传递给 NSTimer 在我的代码中调用的方法。它正在引发异常。我就是这样做的。 Circle 是我的自定义类。

    var circle = Circle()
    var timer = NSTimer.scheduledTimerWithInterval(1.0, target: self, selector: animate, userInfo: circle, repeats: true)

下面是被调用的方法

    func animate(circle: Circle) -> Void{
      //do stuff with circle
    }

注意:该方法与被调用的类在同一个类中。所以我相信我已经正确地设定了目标。

【问题讨论】:

    标签: ios xcode swift nstimer


    【解决方案1】:

    NSTimer 一起使用的选择器被传递给NSTimer 对象,因为它是唯一的参数。将圆形对象作为userInfo 放入其中,您可以在计时器触发时提取它。

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

    【讨论】:

    • 两个参数怎么样?
    • 将两个参数作为元组传递给 userInfo?或者制作一个封装两个参数的自定义结构?我现在不能尝试这个,也许这会给你一个提示。再次询问您是否仍然卡住
    【解决方案2】:

    您的选择器必须是一个字符串,除非它应该是一个 ivar。此外,您的 animate 函数签名错误。以下更改应该会让您再次行动起来:

    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
    }
    

    函数真的不需要返回空元组;不用-> ()也可以写

    我还看到选择器字符串包含在“Selector()”方法中:Selector("animate")。无论哪种方式都可以。

    我自己一直在搞乱NSTimer和闭包,并写了一篇关于它的文章:Using Swift's Closures With NSTimer

    【讨论】:

    • Xcode 中的字符串替换:@"bla bla"; Swift 中的字符串替换:“bla bla”所以这是正确的答案。
    • 似乎仍然不起作用。我收到以下错误消息 *** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:无法识别的选择器发送到实例 0x10da13d60'
    • 无法传递circle参数,但看起来它已经是一个属性了。 try: func animate() { //用 self.circle 做一些事情 }
    • 这就是问题所在。我有很多需要定期动画的圆形对象。所以他们需要被传递到那个方法中
    • selector: "animate" 应该是selector: "animate:"
    猜你喜欢
    • 2011-04-30
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多