NSTimer 问题(闭包、@objc 等)

NSTimer questions (closure, @objc, and etc.)

我是 swift 的新手,我对 swift 甚至是基本的 OOP 有一些疑问(所以如果可以的话,请具体回答,非常感谢!)

所以我正在制作一个具有计时器组件的应用程序,下面的代码片段来自该计时器 class(和视图控制器):

  1. 我有 stop/start 函数和 deinit:
var timer = NSTimer()
...
func start(){
    self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "tick", userInfo: nil, repeats: true)
}
func stop(){
    timer.invalidate()
}
....
deinit(){
    self.timer.invalidate()
}

所以我的第一个问题是,为什么我需要在 deinit 和 start 中而不是在 stop 中调用 self.timer?另外,什么时候调用 deinit 以及它与停止函数有什么不同(在我看来它们都使 NSTimer 无效)?

  1. 还有一个初始化器:
init (duration: Int, handler: (Int) -> ()){
    self.duration = duration
    self.handler = handler
}

并且在视图控制器中调用初始化程序:

private func timerSetUP(hr: Bool, duration: Int){
    timer = Timer(duration: duration){
        (elapsedTime: Int) -> () in
        let timeRemaining = duration - elapsedTime
        println("what is the eT: \(elapsedTime)")
        let timeReStr = self.getHrMinSecLabels(hr, timeremaining: timeRemaining)
    ....}

我的问题是关于闭包的,elapsedTime 是 Timer class 中的一个 属性 并且它只是被传递到视图控制器中的闭包中吗?为什么没有引用定时器 class(如 timer.elapsedTime)?而且我真的不需要这个关闭对吗?我可以有另一个功能做同样的事情(或者使用这个闭包更容易获得 elapsedTime)?

  1. 我的Timer里也有Tick功能class:
@objc func tick(){
    self.elapsedTime++
    self.handler(elapsedTime)
    if self.elapsedTime == self.duration{
        self.stop()
    }
}

这是 self.timer = NSTimer.scheduledTimerWithTimeInterval() 的选择器,选择器只是一个每次定时器触发时都会调用的函数吗?我只需要给 NSTimer.scheduledTimerWithTimeInterval() 选择器函数的字符串名称吗?还有为什么会有@objc,这对我来说就像一个swift函数?

您的问题已加载。让我尝试一次解决一个问题:

why do I need to call self.timer in deinit and start but not in stop

这是个人编码风格。 self.timertimer 相同,假设您没有覆盖实例变量的局部变量。

Also when does deinit get called and what does it do differently than the stop function?

deinit 在 运行 时间释放您的对象时被调用。如果此时你的计时器还在运行ning,它需要先停止它。 stop 只是停止计时器,但将对象保留在内存中。

My question is about the closure, elapsedTime is a property in Timer class...

你需要稍微了解一下闭包。 elapsedTime 是 closure/anonymous 函数的一个参数。当计时器触发时,Timer 对象将其 elapsedTime 属性 传递给该匿名函数。如果像这样重命名它,效果相同:

timer = Timer(duration: duration){
    (t : Int) -> () in
    let timeRemaining = duration - t
    println("what is the eT: \(t)")
    let timeReStr = self.getHrMinSecLabels(hr, timeremaining: timeRemaining)
....}

is a selector just a function that gets called every time the timer fires?

是的。但是你需要指定在什么对象上调用函数(见下一题的target参数)。

And do I just need to give NSTimer.scheduledTimerWithTimeInterval() the string name of the selector function?

是的,像这样:

// Fire the tellTime() function of the current object every second (1000ms)
self.timer = NSTimer.scheduledTimerWithTimeInterval(
                        timeInterval: 1000,
                        target: self,
                        selector: "tellTime",
                        userInfo: nil,
                        repeats: true)

Also why is there @objc, this just looks like a swift function to me?

这是为了让 Objective-C 代码知道您的 Swift 函数。如果您只在 Swift.

中编程,则可以跳过它