使用Swift的Xcode 6.1:由于未捕获的异常'NSUnknownKeyException'而终止应用程序

时间:2015-04-08 03:12:03

标签: ios xcode swift

首先,我是Swift/iOS开发的新手,刚开始学习。我正在尝试创建一个简单的应用播放/暂停音乐。界面有一个播放和暂停按钮,以及用于控制音乐音量的滑块。我搜索了SO并发现了一些类似的帖子,但是我发现它们对我的情况没有帮助。

当我在Xcode中构建并启动应用程序时,我收到了错误:

    2015-04-07 23:04:25.403 Music Player[8772:102170] *** Terminating app due 
to uncaught exception 'NSUnknownKeyException', reason: 

'[<Music_Player.ViewController 0x7f991ad3a160> setValue:forUndefinedKey:]: 
this class is not key value coding-compliant for the key play.'
    *** First throw call stack:
    (
        0   CoreFoundation                      0x000000010a45bf35 __exceptionPreprocess + 165
        1   libobjc.A.dylib                     0x000000010bf9fbb7 objc_exception_throw + 45
        2   CoreFoundation                      0x000000010a45bb79 -[NSException raise] + 9
        3   Foundation                          0x000000010a8737b3 -[NSObject(NSKeyValueCoding) setValue:forKey:] + 259
        4   CoreFoundation                      0x000000010a3a5e80 -[NSArray makeObjectsPerformSelector:] + 224
        5   UIKit                               0x000000010afacc7d -[UINib instantiateWithOwner:options:] + 1506

.....

    22  UIKit                               0x000000010ace7420 UIApplicationMain + 1282
    23  Music Player                        0x0000000109f24afe top_level_code + 78
    24  Music Player                        0x0000000109f24b3a main + 42
    25  libdyld.dylib                       0x000000010c779145 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

我使用 AVAudioPlayer 类来实例化播放和播放音乐的播放器。

   var player: AVAudioPlayer = AVAudioPlayer()

    @IBAction func play(sender: AnyObject) {
        var audioPath = NSString(string: NSBundle.mainBundle().pathForResource("music", ofType: "mp3")!) //file: music.mp3

        var error: NSError? = nil

        //instantiate the player
        player = AVAudioPlayer(contentsOfURL: NSURL(string: audioPath), error: &error) //error pointer
        player.prepareToPlay()
        player.play()
    }


    @IBAction func pause(sender: AnyObject) {
        player.pause()
    }

除了以下代码之外,我还没有使用滑块做任何事情:

@IBOutlet var slider: UISlider!
@IBAction func sliderChanged(sender: AnyObject) {
    }

GUI附在下面: enter image description here

1 个答案:

答案 0 :(得分:1)

if let resourceUrl = NSBundle.mainBundle().URLForResource("1", withExtension: "mp3") {
        if NSFileManager.defaultManager().fileExistsAtPath(resourceUrl.path!) {

            var error: NSError? = nil

            //instantiate the player
            player = AVAudioPlayer(contentsOfURL: resourceUrl, error: &error)
            player.prepareToPlay()
            player.play()
        }
    }

更新您的代码,以避免在文件不存在时崩溃。

this class is not key value coding-compliant for the key play.

意味着如果您的nib(xib文件)中有一个控件链接到视图控制器中的属性(IBOutlet)或方法(IBAction),并且您已删除或重命名了属性或方法,则运行时可以找不到它,因为它已被重命名,因此崩溃。

HERE我为你创建了完整的工作项目。