简体   繁体   English

按下按钮时线程1:EXC_BAD_ACCESS(code = 1,地址= 0X48)

[英]Thread1:EXC_BAD_ACCESS(code=1, address = 0X48) when button is pressed

var buttonTapPlayer = AVAudioPlayer()


override func viewDidLoad() {
        super.viewDidLoad()

    DispatchQueue.global(qos: .background).async {
        do{
            let correctSoundUrl: URL = URL(fileURLWithPath: Bundle.main.path(forResource: "buttonTap", ofType: "wav")!)
            self.buttonTapPlayer = try AVAudioPlayer(contentsOf: correctSoundUrl)
            self.buttonTapPlayer.prepareToPlay()
        }
        catch{}
    }
}


@IBAction func buttonPressed(_ sender: UIButton) {

      self.buttonTapPlayer.play()
        performSegue(withIdentifier: "showDetail", sender: sender)

}

I have the above code in my swift project. 我的快速项目中有上面的代码。 My project crashes the very first time I run the project in simulator at self.buttonTapPlayer.play() with the following error: 我第一次在模拟器中通过self.buttonTapPlayer.play()在模拟器中运行项目时,项目崩溃,并出现以下错误:

Thread1:EXC_BAD_ACCESS(code=1, address = 0X48) 线程1:EXC_BAD_ACCESS(代码= 1,地址= 0X48)

However, when I re-run it, everything is fine. 但是,当我重新运行它时,一切都很好。 How do I resolve this? 我该如何解决?

You can't do it. 你做不到 You've build your buttonTapPlayer in a background thread and you try to call it from the main thread (to IBAction method). 您已经在后台线程中构建了buttonTapPlayer ,并尝试从主线程(到IBAction方法)中调用它。 The compiler crashed to play() because your player is not yet ready. 由于您的播放器尚未准备就绪,编译器无法运行play()

To avoid this, you could build your player inside: 为了避免这种情况,您可以在内部构建播放器:

DispatchQueue.main.async {
   // build your stuff to the main thread
}

or simply remove DispatchQueue.global(qos: .background).async {} 或仅删除DispatchQueue.global(qos: .background).async {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM