无法识别的选择器已发送到实例NSTimer Swift [英] Unrecognized selector sent to instance NSTimer Swift

查看:106
本文介绍了无法识别的选择器已发送到实例NSTimer Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to developing an app that includes a simple Stopwatch feature. I'm using Xcode 6 and the Swift language. Here is the code in 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 Simulator中)时,当我按下按钮(执行秒表功能)时,该应用程序就会崩溃.该错误始终显示为

Every time I run the app (within iOS Simulator), the app crashes when I press the button (execute the Stopwatch function). The error always reads

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编程还很陌生,所以请帮忙!

I have no idea why this is happening and I'm pretty new to iOS programming, so please help!

推荐答案

让updateTime成为类方法.
并且,如果它在纯Swift类中,则需要使用@objc在该方法的声明前添加前缀:

let updateTime be a class method .
And if it's in a pure Swift class you'll need to preface that method's declaration with @objc like:

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

     }
}

这篇关于无法识别的选择器已发送到实例NSTimer Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆