class Sound {
var soundID: SystemSoundID = 0
var isPlaying = false
func playSound() {
let soundURL = ...
AudioServicesCreateSystemSoundID(soundURL, &soundID)
AudioServicesPlaySystemSound(soundID)
self.isPlaying = true
AudioServicesAddSystemSoundCompletion(soundID, nil, nil, { soundID, inClientData in
let me = unsafeBitCast(inClientData, Sound.self)
me.audioServicesPlaySystemSoundCompleted(soundID) -> Error: Thread 1: EXEC_BAD_ACCESS
}, UnsafeMutablePointer(unsafeAddressOf(self)))
}
func audioServicesPlaySystemSoundCompleted(soundID: SystemSoundID) {
print("Completion")
isPlaying = false
AudioServicesRemoveSystemSoundCompletion(soundID)
AudioServicesDisposeSystemSoundID(soundID)
}
}
错误:线程1:EXEC_BAD_ACCESS(代码= 2,地址= xxx)
我真的不知道为什么会出现这个错误。我调试了代码,me
的地址与传入的self
完全相同。
答案 0 :(得分:0)
好吧,似乎我需要像这样保留self
的值,并且unsafe
方法不会自动保留实例。怪异。
AudioServicesAddSystemSoundCompletion(soundID, nil, nil, { (soundID, inClientData) -> Void in
let me = Unmanaged<Sound>.fromOpaque(COpaquePointer(inClientData)).takeRetainedValue()
me.isPlaying = false
}, UnsafeMutablePointer(Unmanaged.passRetained(self).toOpaque()))
受此answer启发,但我没有使用unretained
方法,而是使用了retained
方法。