我正在尝试开发一个包含简单秒表功能的应用程序.我正在使用
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编程很新,所以请帮忙!
解决方法
让updateTime成为一个类方法.
如果它是在一个纯粹的Swift类中,你需要在@objc前面说明该方法的声明,如:
如果它是在一个纯粹的Swift类中,你需要在@objc前面说明该方法的声明,如:
class A { @objc func updateTime(timer:NSTimer) { } }