最近在使用AVAudioPlayer播放音频时,发现有
内存泄漏的现象,我的代码如下:
-(id)init
{
if (self = [super init]) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"GameOver" ofType:@"mp3"];
NSError *error = nil;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
audioPlayer.delegate = self;
[audioPlayer prepareToPlay];
audioPlayer.numberOfLoops = -1;
[audioPlayer play];
}
return self;
}
-(void)dealloc
{
if (audioPlayer && [audioPlayer isPlaying]) {
[audioPlayer stop];
}
[audioPlayer release];
audioPlayer = nil;
[super dealloc];
}
跟踪Instruments工具中的泄漏情况,发现都是在
NSURL或NSData泄漏了,在stackoverflow发现有人这么说(帖子:http://stackoverflow.com/questions/12498015/leak-from-nsurl-and-avaudioplayer-using-arc):
Looks to be a leak in Apple's code... I tried using both
-
-[AVAudioPlayer initWithData:error:]and -[AVAudioPlayer initWithContentsOfURL:error:]
In the first case, the allocated
AVAudioPlayer instance retains the passed in
NSData. In the second, the passed in
NSURL is retained:
也就是说使用AVAudioPlayer播放音频时,NSData或NSURL被retain了,所以,我在dealloc方法中将其release,内存泄漏就解决了:
-(void)dealloc
{
[audioPlayer.url release];
if (audioPlayer && [audioPlayer isPlaying]) {
[audioPlayer stop];
}
[audioPlayer release];
audioPlayer = nil;
[super dealloc];
}
本文介绍了一位开发者在使用AVAudioPlayer播放音频时遇到的内存泄漏问题,并提供了详细的代码示例及解决方法。

1277

被折叠的 条评论
为什么被折叠?



