是否允许从 NSTimer 调用静态方法?编译器不允许这样做,并提示神秘的“调用中的额外参数‘选择器’。
struct MyStruct {
static func startTimer() {
NSTimer.scheduledTimerWithTimeInterval(1.0, target: MyStruct.self, selector: "doStuff", userInfo: nil, repeats: true)
}
static func doStuff() {
println("Doin' it.")
}
}
MyStruct.startTimer()
当然,这很好用......
class MyClass {
func startTimer() {
NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "doStuff", userInfo: nil, repeats: true)
}
func doStuff() {
println("Doin' it.")
}
}
var instanceOfClass = MyClass()
instanceOfClass.startTimer()
我只是语法错误,还是不允许?
最佳答案
NSTimer
利用 Objective-C 运行时来动态调用方法。当声明一个 struct
时,你正在使用 Swift runtime,因此 NSTimer
是不可能合作的。结构不同于类,您可以阅读有关它们的更多信息 here .
此外,static
函数等同于 Objective-C 中的类方法,因此如果这是您最初的目标,那么以下内容就足够了:
class MyClass: NSObject {
class func startTimer() {
NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "doStuff", userInfo: nil, repeats: true)
}
class func doStuff() {
println("Doin' it.")
}
}
MyClass.startTimer()
关于ios - 从 NSTimer 调用静态方法。可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29308661/