使用 NSTimer 的重复函数失败,目标为:self in Swift

Repeat function using NSTimer fails with target: self in Swift

我找到 this question 并尝试将代码复制到我的 Xcode 项目,但我收到以下错误消息。

error: use of unresolved identifier 'self'

正确的方法是什么?

编辑: 这里是在操场上测试的代码:

    //: Playground - noun: a place where people can play

import Cocoa
import Foundation

func sayHello() {
    print("hello World")
}

var SwiftTimer = NSTimer()
SwiftTimer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("sayHello"), userInfo: nil, repeats: true)

通常使用大写的属性名称被认为是一种不良态度,你应该使用swiftTimer。

顶级不允许使用这些表达式:

var swiftTimer = NSTimer()
swiftTimer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("sayHello"), userInfo: nil, repeats: true)

您必须将它放在函数中,例如:

override func viewDidLoad() {
        super.viewDidLoad()
        var swiftTimer = NSTimer()
        swiftTimer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("sayHello"), userInfo: nil, repeats: true)
}

self指的是为其定义了方法(class中定义的函数)的对象,因此只能在方法中使用。 (相当于C++中的this/Java/Javascript。)在你的代码中,sayHello()是一个全局函数,不是方法,所以没有self可以引用.

为了使 scheduledTimerWithTimeInterval() 函数调用与这些参数一起工作,必须在实例方法中调用它,以便有一个 self,并且 class 必须有名为 sayHello().

的方法

您也可以将 target: 更改为另一个对象,只要该对象具有 sayHello() 方法即可。

基本上,异步计时器在 Playground 中不起作用,并且由于 Playground 的顶层不是 class,所以没有 self 属性。

在操场上测试NSTimer

  • 将计时器包装在 class 中。
  • 导入XCPlaygound.
  • 添加 XCPlaygroundPage.currentPage.needsIndefiniteExecution = true 以启用对异步任务的支持。