在闭包之外对自定义的错误访问

时间:2016-07-14 01:54:52

标签: swift closures

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完全相同。

1 个答案:

答案 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方法。

相关问题