【问题标题】:Swift nstimer accessing function other classSwift nstimer 访问函数其他类
【发布时间】:2016-06-29 22:08:14
【问题描述】:

在另一个类中作为 NStimer 的选择器运行该函数时遇到问题。

class VariClass
{
  func updateUILoop()
    {
         print("updating UI")
    }
}

在我的应用委托中

let values = VariClass()

在我拥有的 appdelegate 中。

let timer = NSTimer(fireDate: NSDate(), interval: 5, target: self, selector: #selector(values.updateUILoop), userInfo: nil, repeats: true)

如果我手动运行该功能,它会完美运行。

getvalues.updateUILoop()

【问题讨论】:

    标签: swift class nstimer


    【解决方案1】:

    您希望NSTimervalues 对象上调用func updateUILoop,因此计时器回调的目标应该是values,而不是self

    let timer = NSTimer(fireDate: NSDate(), interval: 5, target: self.values, selector: #selector(VariClass.updateUILoop), userInfo: nil, repeats: true)
    

    【讨论】:

    • 我收到此错误。 “'#selector' 的参数是指未暴露给 Objective-C 的方法”。
    • @nyitguy 我不确定@objc 标记背后的原因。我唯一的猜测是选择器保留在 Swift 中只是为了实现 Objective-C 的互操作性。在所有其他情况下,它们被闭包所取代。因此,Swift 语言设计者希望程序员用特殊标签标记符合选择器结构的函数,以明确意图。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-02
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 2013-08-18
    • 1970-01-01
    相关资源
    最近更新 更多