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

标签 swift nstimer

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

error: use of unresolved identifier 'self'

什么是正确的方法?

编辑:这里是在 Playground 上测试过的代码:

    //: 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)
}

关于swift - 使用 NSTimer 的重复函数失败,目标为 : self in Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37375939/

相关文章:

ios - Swift:从另一个类调用函数以出现在同一个 WebView 中

ios - Swift:无法下标类型为 '[UIViewController]?' 的值

cocoa - 当 runloop 被阻塞时 NSTimer 不会触发

ios - 定义一个变量为AnyObject,以便以后可以更改为NSTimer--Swift

iphone - iPhone 后台运行定时器功能

ios - 在 Swift 中,如何检测 UITextView 中空格键的双击?

arrays - 将字符串编码数组转换为对象

ios - 使用按钮以编程方式更改方向 - iOS

ios - 在 swift 中使用延迟调用数组项 - 获取 UIResponder 错误

iphone - 在定义的秒数后调用函数而不使用计时器