ios - 从 NSTimer 调用静态方法。可能吗?

标签 ios swift nstimer static-methods

是否允许从 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/

相关文章:

iphone - iPhone 中的页面 curl

ios - UIWebView loadHtmlString 无法在设备上运行

ios - 在 iOS 中以特定时间间隔调用操作

ios - Ntimer 实现

ios - 为什么这个工具栏中的按钮没有触发它们的目标操作?

ios - 使 iOS UISegmentedcontrol 中的标签跨越 2 行

swift - danielgindi/Charts - iOS - 在条形图上的特定栏上方设置标签

ios - 如何将@Environment(\.colorScheme) 设置回系统/自动?

json - 无法使用类型为“(Codable.Type?

swift - NSTimer 在此函数中无效时不会停止