首页 > 开发 > iOS > 正文

iOS6下AVAudioPlayer内存泄露

2017-09-08 14:04:08  来源:网友分享

我的视图控制器里放了一个按钮。main bundle里放了一个1.mp3,按钮每按一次就停止上次的音乐播放,开始下次音乐播放;

此代码在iOS4/5工作正常,iOS6中有严重的内存泄露。如果1.mp3有5M大,iOS6下每次播放就会有5M的内存不能释放。

我在iOS6下的使用方法错了吗?求指导

代码如下(开启ARC):

@implementation ViewController{    AVAudioPlayer *_player;}- (void)play{    if (_player)    {        [_player stop];        _player = nil;    }        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"test.app/1.mp3"];    NSData *musicData = [[NSData alloc] initWithContentsOfFile:path];    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:musicData error:nil];    player.volume = 1;    if (player)    {        _player = player;    }}- (void)viewDidLoad{    [super viewDidLoad];    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];    button.frame = CGRectMake(100, 100, 100, 100);    [button setTitle:@"play" forState:UIControlStateNormal];    [button addTarget:self action:@selector(play) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:button];}@end

解决方案

苹果iOS6运行时的bug,已反馈给苹果:https://bugreport.apple.com/cgi-bin/W...

相同问题:https://devforums.apple.com/thread/16...

苹果修复之前替代方法:将data写入缓存文件,用initWithContentsOfURL:替代initWithData: