使用选择器进行本地功能

时间:2014-08-13 16:47:38

标签: swift

我想设置一个触发一些本地函数的计时器,以便count和scheduledAction()对外部不可见。在以下情况中,scheduledAction是无法识别的选择器。什么是一个好方法呢?

func SomeFunc() {
    var count = 0
    var timer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "scheduledAction", userInfo: nil, repeats: true)
    func scheduledAction() {
        count++
        if count < 10 {
            // do something
        }
        else {
            timer = nil
        }
    }
}

1 个答案:

答案 0 :(得分:1)

函数scheduledAction应该在SomeFunc的主体之外,即:

func SomeFunc() {
    var timer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "scheduledAction", userInfo: nil, repeats: true)

}

func scheduledAction() {

}

&#39; scheduledTimerWithTimeInterval&#39;的目标参数中的self。指的是包含SomeFunc的类。

如果要在选择器中访问timer变量,则需要使用选择器&#34; scheduledAction:&#34;并让scheduledAction采用NSTimer参数,例如。

func SomeFunc() {
    var timer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "scheduledAction", userInfo: nil, repeats: true)

}

func scheduledAction(timer : NSTimer) {

}

但更好的模式是将其封装为一个类:

class SomeClass() {
    var count = 0
    var timer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "scheduledAction", userInfo: nil, repeats: true)
    func scheduledAction() {
        count++
        if count < 10 {
            // do something
        }
        else {
            timer = nil
        }
    }
}

为了让count和scheduledAction对外界不可见,只需将它们标记为私有!