首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > Iphone >

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

2012-12-31 
iPhone开发中使用AVAudioPlayer出现内存泄漏的解决办法?最近在使用AVAudioPlayer播放音频时,发现有内存泄

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

?


最近在使用AVAudioPlayer播放音频时,发现有内存泄漏的现象,我的代码如下:iPhone开发中使用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,内存泄漏就解决了:
    iPhone开发中使用AVAudioPlayer出现内存泄漏的解决方法
    -(void)dealloc{    [audioPlayer.url release];        if (audioPlayer && [audioPlayer isPlaying]) {        [audioPlayer stop];    }        [audioPlayer release];    audioPlayer = nil;    [super dealloc];}
    ?

    ?

热点排行