0

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

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 output 仍然会发生变化。我认为它正在发生,因为传递的值是可选的,那么如果这是问题,我该如何让它不是可选的呢?

4

1 回答 1

3

NSTimerscheduledTimerWithTimeInterval userInfo参数不是标准参数,尽管您可以设置userInfo为 hold AnyObject,但不能像使用大多数函数那样简单地传递参数,因为scheduledTimerWithTimeInterval的选择器只能NSTimer作为其唯一的参数传递。因此,如果您想访问存储在计时器中的值,则secondFunction: 必须指定一个作为其参数,例如:NSTimeruserInfo

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)");
}
于 2014-12-17T03:36:27.440 回答