简体   繁体   中英

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:

Thread1:EXC_BAD_ACCESS(code=1, address = 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). The compiler crashed to play() because your player is not yet ready.

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 {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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