SWIFT致命错误:在解包可选值时意外发现了nil (lldb)
SWIFT致命错误:在解包可选值时意外发现了nil (lldb)
我试图运行这段Swift代码,但输出以下错误:"fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)"。
这是代码:
//
// PlaySoundsViewController.swift
// Revoice
//
// Created by Leonardo Barazza on 16/04/15.
// Copyright (c) 2015 Leonardo Barazza. All rights reserved.
//
import UIKit
import AVFoundation
class PlaySoundsViewController: UIViewController {
var audioPlayer: AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
// 在加载视图后进行任何其他设置。
if var filePath = NSBundle.mainBundle().pathForResource("movie_quote", ofType: "mp3") {
var filePathUrl = NSURL.fileURLWithPath(filePath)
audioPlayer = AVAudioPlayer(contentsOfURL: filePathUrl, error: nil)
} else {
println("文件路径为空")
}
}
@IBAction func playSlowly(sender: UIButton) {
audioPlayer.play()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// 释放可以重新创建的任何资源。
}
/*
// MARK: - Navigation
// 在基于故事板的应用程序中,通常希望在导航之前进行一些准备
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// 使用segue.destinationViewController获取新的视图控制器。
// 将选定的对象传递给新的视图控制器。
}
*/
}
你能帮我吗?
提前谢谢。
这个问题的出现原因是在代码中创建了一个只有一个实例变量的AVAudioPlayer,该变量被定义为非可选类型(使用了感叹号!)。当编译器使用尚未创建的实例时,就会出现错误。
根据你提供的代码,只有一个地方使用了AVAudioPlayer的实例,即func playSlowly()。但是由于没有提供调试器信息,我只能猜测错误可能出现在audioPlayer.play()这个地方。
我认为代码中的if var filePath = NSBundle.mainBundle().pathForResource("movie_quote", ofType: "mp3")这一行导致了无法定义audioPlayer实例的失败。
你应该检查filePath的定义是否正确。
解决方法:
1. 确保文件"movie_quote.mp3"存在于项目的资源中。
2. 确保filePath的定义正确,它应该是一个有效的文件路径。
3. 使用可选绑定来创建audioPlayer实例,以便在filePath无效时避免出现错误。
代码示例:
if let filePath = NSBundle.mainBundle().pathForResource("movie_quote", ofType: "mp3") {
let audioUrl = NSURL(fileURLWithPath: filePath)
do {
audioPlayer = try AVAudioPlayer(contentsOfURL: audioUrl)
} catch {
print("Error creating audio player: \(error)")
}
} else {
print("File not found")
}
通过上述步骤,你应该能够解决这个问题并避免出现"fatal error: unexpectedly found nil while unwrapping an Optional value"的错误。
在上述代码中,问题出现在audioPlayer
属性上:它被定义为一个隐式解包的AVAudioPlayer
可选类型,因此无论何时访问它,它都不能为nil
(否则会抛出运行时异常,因为隐式解包)。
问题在于,只有在filePath != nil
时,你才会创建一个实例(audioPlayer != nil
)。你有检查过filePath
是否为nil
吗?
顺便说一下,你可以通过使用可选链来跳过这个问题:
func playSlowly(sender: UIButton) {
if audioPlayer?.play() == nil {
println("audioPlayer is nil")
}
}