【问题标题】:Unrecognized selector sent to instance NSTimer Swift无法识别的选择器发送到实例 NSTimer Swift
【发布时间】:2014-11-23 10:55:22
【问题描述】:

我正在尝试开发一个包含简单秒表功能的应用。我正在使用 Xcode 6 和 Swift 语言。这是FirstViewController中的代码

@IBAction func Stopwatch (Sender:UIButton) { 

var startTime = NSTimeInterval()

    func updateTime(timer:NSTimer) {

        //Find Current TIme

        var currentTime = NSDate.timeIntervalSinceReferenceDate()

        //Find the difference between current time and start time

        var elapsedTime :NSTimeInterval = currentTime - startTime

        //calculate the minutes in elapsed time.
        let minutes = UInt(elapsedTime / 60.0)
        elapsedTime -= (NSTimeInterval(minutes) * 60)

        //calculate the seconds in elapsed time.
        let seconds = UInt(elapsedTime)
        elapsedTime -= NSTimeInterval(seconds)

        //find out the fraction of milliseconds to be displayed.
        let hours = UInt(elapsedTime * 100)

        let strMinutes = minutes > 9 ? String(minutes):String(minutes)
        let strSeconds = seconds > 9 ? String(seconds):String(seconds)
        let strHours = hours > 9 ? String(hours):String(hours)

        //assign text to Label
        elapsedTimeLabel.text = "You have slept for \(strHours)"
    }

    //Timer 
    var timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: Selector("updateTime:"), userInfo: nil, repeats: true)
    startTime = NSDate.timeIntervalSinceReferenceDate()

}
}

每次我(在 iOS 模拟器中)运行应用程序时,当我按下按钮(执行秒表功能)时,应用程序就会崩溃。错误总是显示

2014-11-23 11:44:53.617 Sleep[9630:644637] -[Sleep.FirstViewController updateTime:]: 
unrecognized selector sent to instance 0x7ff6d9676e80
2014-11-23 11:44:53.622 Sleep[9630:644637] *** Terminating app due to uncaught exception 
'NSInvalidArgumentException', reason: '-[Sleep.FirstViewController updateTime:]: unrecognized 
selector sent to instance 0x7ff6d9676e80'
*** First throw call stack:

我不知道为什么会这样,而且我对 iOS 编程还很陌生,所以请帮忙!

【问题讨论】:

    标签: ios swift nstimer stopwatch


    【解决方案1】:

    让 updateTime 成为一个类方法。
    如果它在一个纯 Swift 类中,您需要在该方法的声明前加上 @objc,例如:

    class A {
         @objc func updateTime(timer:NSTimer) {
    
         }
    }
    

    【讨论】:

    • 似乎不需要@objc 标志,至少在 Swift 1.2 中是这样。但是,我遇到了同样的错误,因为我的选择器签名错误。它需要设置为接收 NSTimer。例如func mySelector(timer: NSTimer)
    【解决方案2】:

    您已将updateTime 定义为Stopwatch 的本地函数,因此它在其范围之外不可用。您应该在班级级别移动它(与Stopwatch 相同)以便可以访问。

    我注意到有一些局部变量可能应该是实例属性。

    【讨论】:

      【解决方案3】:

      另一种可能性:确保您的选择器函数没有throw,因为这也会给您一个无法识别的选择器异常:

      func mySelector(timer: NSTimer) throws {
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-16
        相关资源
        最近更新 更多