我有 AVAudioPlayer
实例:
var audioPlayer: AVAudioPlayer!
self!.audioPlayer = AVAudioPlayer(data: fileData, error: &error)
self!.audioPlayer?.numberOfLoops = -1
self!.audioPlayer?.delegate = self
if (self?.audioPlayer?.prepareToPlay() != false) {
println("Successfully prepared for playing")
} else {
println("Failed to prepare for playing")
}
我需要为此
AVAudioPlayer
禁用 ARC。 Unmanaged
没有很好的文档记录,所以很难做到这一点。这是我尝试过的:var audioPlayer: Unmanaged<AVAudioPlayer>!
//Stuck after creating nil instance, what to do now?
self!.audioPlayer = AVAudioPlayer(data: fileData, error: &error)
self!.audioPlayer?.numberOfLoops = -1
self!.audioPlayer?.delegate = self
if (self?.audioPlayer?.prepareToPlay() != false) {
println("Successfully prepared for playing")
} else {
println("Failed to prepare for playing")
}
最佳答案
你应该写:
// Properties in your class
var unmanagedAudioPlayer: Unmanaged<AVAudioPlayer>
var audioPlayer : AVAudioPlayer!
// code
self.audioPlayer = AVAudioPlayer(...)
self.unmanagedAudioPlayer = Unmanaged.passRetained(self.audioPlayer)
现在您可以像往常一样使用
self.audioPlayer
作为 AVAudioPlayer
(或者 AVAudioPlayer!
如果您愿意,但我不明白为什么)。self.unmanagedAudioPlayer
保留了 self.audioPlayer
的保留引用,因此它不能被 ARC 释放。当你完成这个
AVAudioPlayer
对象后,你可以调用 self.unmanagedAudioPlayer.release()
(或 autorelease
)来释放它,就像你在 Objective-C 中做的一样。实际上,您不需要单独存储
self.audioPlayer
,因为您始终可以通过 unmanagedAudioPlayer.takeUnratainedValue()
获取它,但它是一个很好的别名,可以使您的代码更具可读性。关于ios - Swift:非托管 AVAudioPlayer,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31492099/