Iphone上的滑块崩溃程序,但在模拟器上工作
Posted
技术标签:
【中文标题】Iphone上的滑块崩溃程序,但在模拟器上工作【英文标题】:Slider Crashes program on Iphone, but worked on simulator 【发布时间】:2017-08-03 22:58:26 【问题描述】:我正在使用此代码来跟踪和更新滑块值,然后转换为字符串并显示在标签上。问题是,此代码在模拟器上工作,但在实际手机上崩溃。出现错误“在展开可选值时意外发现 nil”。我不知道是什么原因造成的,任何帮助将不胜感激。
func updateSlider()
sliderBar.value = Float(CMTimeGetSeconds(self.audioPlayer.currentItem!.currentTime()))
let currentTime = Int((CMTimeGetSeconds(self.audioPlayer.currentItem!.currentTime())))
let duration = Int((CMTimeGetSeconds(self.audioPlayer.currentItem!.asset.duration)))
//let total = currentTime - duration
let minutes = currentTime/60
let seconds = currentTime - minutes * 60
let minutes2 = duration/60
let seconds2 = duration - minutes2 * 60
self.lblPastTime.text = NSString(format: " %02d:%02d / %02d:%02d ",minutes2,seconds2, minutes,seconds) as String
【问题讨论】:
看起来该代码中唯一可能的 Optional 是self.lblPastTime
。我建议它可能为零。
@Michael 如果是这样,它不会在模拟器上也崩溃吗?
【参考方案1】:
避免强制展开变量是避免此类错误的好方法:
func updateSlider ()
guard let currentItem = self.audioPlayer.currentItem else return
sliderBar.value = Float(CMTimeGetSeconds(currentItem.currentTime()))
let currentTime = Int((CMTimeGetSeconds(currentItem.currentTime())))
let duration = Int((CMTimeGetSeconds(currentItem.asset.duration)))
//let total = currentTime - duration
let minutes = currentTime/60
let seconds = currentTime - minutes * 60
let minutes2 = duration/60
let seconds2 = duration - minutes2 * 60
self.lblPastTime.text = NSString(format: " %02d:%02d / %02d:%02d ",minutes2,seconds2, minutes,seconds) as? String
使用guard let
我可以安全地解包变量,所以如果它是nil
,函数就会返回。
【讨论】:
【参考方案2】:回答
必须使用 audioPlayer.currentTime()
而不是 audioPlayer.currentItem!.currentTime()
func updateSlider()
sliderBar.value = Float(CMTimeGetSeconds(audioPlayer.currentTime()))
//sliderBar.value = Float(CMTimeGetSeconds(self.audioPlayer.currentItem!.currentTime()))
let currentTime = Int((CMTimeGetSeconds(self.audioPlayer.currentItem!.currentTime())))
let duration = Int((CMTimeGetSeconds(self.audioPlayer.currentItem!.asset.duration)))
//let total = currentTime - duration
let minutes = currentTime/60
let seconds = currentTime - minutes * 60
let minutes2 = duration/60
let seconds2 = duration - minutes2 * 60
self.lblPastTime.text = NSString(format: " %02d:%02d / %02d:%02d ",minutes2,seconds2, minutes,seconds) as String
【讨论】:
以上是关于Iphone上的滑块崩溃程序,但在模拟器上工作的主要内容,如果未能解决你的问题,请参考以下文章
设备和模拟器上的调试工作时,临时 iPhone SIGSEGV 崩溃
Flutter App 在模拟器(Iphone 12 mini)上完美运行,但在设备上崩溃(Iphone 8 plus)