Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios NSBundle.pathForResource的Swift可选绑定正在返回垃圾?_Ios_Swift_Nsbundle - Fatal编程技术网

Ios NSBundle.pathForResource的Swift可选绑定正在返回垃圾?

Ios NSBundle.pathForResource的Swift可选绑定正在返回垃圾?,ios,swift,nsbundle,Ios,Swift,Nsbundle,我是一名长期的iOS开发人员,但在swift中才刚刚起步。我正在做一个测试程序,可以裁剪图像。我的进步很快,但出现了一些非常奇怪的情况 当用户裁剪图像并将其保存到他们的照片库时,我尝试播放快门声音 我写了一个函数,为我的快门声音创建一个AVAudioPlayer。该函数被惰性存储属性“调用”,但该细节不重要 函数如下所示: func loadShutterSoundPlayer() -> AVAudioPlayer? { let theMainBundle = NSBundle.mai

我是一名长期的iOS开发人员,但在swift中才刚刚起步。我正在做一个测试程序,可以裁剪图像。我的进步很快,但出现了一些非常奇怪的情况

当用户裁剪图像并将其保存到他们的照片库时,我尝试播放快门声音

我写了一个函数,为我的快门声音创建一个AVAudioPlayer。该函数被惰性存储属性“调用”,但该细节不重要

函数如下所示:

func loadShutterSoundPlayer() -> AVAudioPlayer?
{
  let theMainBundle = NSBundle.mainBundle()
  let filename = "Shutter sound"
  let fileType = "mp3"
  if let soundfilePath = theMainBundle.pathForResource(filename, 
    ofType: fileType)
  {
    let fileURL = NSURL.fileURLWithPath(soundfilePath)
    return AVAudioPlayer.init(contentsOfURL: fileURL, error: nil)
  }
  else
  {
    return nil
  }
}
使用上述可选绑定编写时,if let soundfilePath位认为它成功,并在大括号内执行条件代码,但soundfilePath中的结果值是垃圾。有时是随机字符,有时是方法名,等等。这就像NSBundle方法pathForResource:ofType:上的内存策略释放对象并创建僵尸

如果我将代码重写为不使用可选绑定,它将按预期工作:

func loadShutterSoundPlayer() -> AVAudioPlayer?
{
  let theMainBundle = NSBundle.mainBundle()
  let filename = "Shutter sound"
  let fileType = "mp3"
  let soundfilePath: String? = theMainBundle.pathForResource(filename, 
    ofType: fileType)
  if soundfilePath != nil
  {
    let fileURL = NSURL.fileURLWithPath(soundfilePath!)
    return AVAudioPlayer.init(contentsOfURL: fileURL, error: nil)
  }
  else
  {
    return nil
  }
}

我是不是遗漏了什么?在我看来,这有点像编译器bug或NSBundle方法pathForResource:ofType:定义中的bug,它生成了错误的ARC代码

您的代码在两种情况下是正确的。可能是XCode错误。您的XCode的版本是什么?。尝试重新启动XCode。或者添加一个NSLog来显示您的soundFilePath的值:NSLogfile%@,soundFilePath我正在使用Xcode 6.2,发布版本Build 6C131e。我没有记录soundFilePath的输出,但我已经在调试器中查看了它。当我运行代码的可选绑定版本时,它是垃圾。非常奇怪。我还建议使用println或NSLog打印路径。调试器变量视图有时是错误的。马丁,谢谢你的参与。当我对@HoaParis'的评论做出回应时,我有着同样的想法。好吧,这真让人恼火。我把崩溃的代码放回原处,放入一个println,它显示正确,代码现在可以工作了。现在看来它决定停止失败了,是的,我以前退出过Xcode,甚至重新启动了我的Mac