iPhone开发中使用AVAudioPlayer出现内存泄漏的解决办法

 


最近在使用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];
}
 


 

你可能感兴趣的:(iPhone开发)