【问题标题】:UserInfo in NSTimer not passing correct information - SwiftNSTimer 中的 UserInfo 没有传递正确的信息 - Swift
【发布时间】:2014-12-17 03:24:16
【问题描述】:

这是我正在尝试做的一些示例代码。

func firstFunction() {
    var timer = NSTimer.scheduledTimerWithTimeInterval(0.6, target: self, selector: Selector("secondFunction:"), userInfo: self.data!.getInfo(), repeats: false);
    println("Info: \(timer.userInfo)");
}

func secondFunction(value: Int) {
    println("Called with \(value)");
}

以下是输出: Info: Optional(( 2 ))Called with 140552985344960

用############# 调用也是不断变化的。即使我只使用一个数字来代替self.data!.getInfo,我仍然会得到Info: Optional(2) 作为输出,并且Called with 输出仍然会发生变化。我认为它正在发生,因为传递的值是可选的,那么如果这是问题,我该如何使它不是可选的呢?

【问题讨论】:

  • secondFunction 应该有一个 NSTimer 作为它的参数,如果你想获取定时器的用户信息...
  • 我尝试使用 NSDictionary 来存储数据,但没有任何区别。我见过其他例子,其中 userInfo 能够将单个参数作为对象。

标签: ios swift selector nstimer userinfo


【解决方案1】:

NSTimerscheduledTimerWithTimeInterval userInfo 参数在某种意义上不是标准参数,尽管您可以将userInfo 设置为持有AnyObject,但您不能简单地通过像使用大多数函数一样在参数中,因为scheduledTimerWithTimeInterval 的选择器只能 传递NSTimer 作为其唯一的参数。所以你的secondFunction:必须指定一个NSTimer作为它的参数,如果你想访问你存储在计时器的userInfo中的值,例如:

func firstFunction() {
    var timer = NSTimer.scheduledTimerWithTimeInterval(0.6, target: self, selector: Selector("secondFunction:"), userInfo: self.data!.getInfo(), repeats: false);
    println("Info: \(timer.userInfo)");
}

func secondFunction(timer: NSTimer) {
    var value = timer.userInfo as Int
    secondFunction(value)
}

// Function added based on your comment about
// also needing a function that accepts ints
func secondFunction(value: Int) {
    println("Called with \(value)");
}

【讨论】:

  • self.data!.getInfo() 是我调用的通用函数,而不是 NSTimer 的 getInfo 函数。我以为我在暗示当我显示输出是Info: Optional(2) 时。所以我不希望 NSTimer 作为参数,而是其他函数的输出。
  • @Ricca 老实说,试试这段代码看看我的意思。该函数的输出实际上将包含在 NSTimer 的 userInfo 属性中,就像您尝试做的那样。
  • @Ricca 然后你需要两个单独的函数接受两个单独的参数。我将更新以向您展示如何。附言同样,您不是“应该”能够将整数传递给 scheduleTimerWithTimeInterval 选择器函数。
  • @Ricca 更新以向您展示如何为 NSTimer scheduledTimerWithTimeInterval 案例和您显然需要在其他地方调用的函数实现函数。
  • 这看起来像是我可以使用的东西。至少在我看来,我希望能够像函数一样传递参数。那好吧。感谢您的帮助。
猜你喜欢
  • 2016-07-21
  • 1970-01-01
  • 2015-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多