`
wsqwsq000
  • 浏览: 674711 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

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];
}
 


 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics