检测/修复内存泄漏 [英] Detecting/Fixing Memory Leaks

查看:81
本文介绍了检测/修复内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经完成了对项目的编码,但是当我在客户端中提交我的源代码时,就对其进行了测试,然后检测到内存泄漏.我已经在Instruments using Leaks中进行了测试. 我遇到的问题是在我的AVPlayerAVAudioPlayer以及我的AppDelegate中. 我应该在这方面找到替代方法吗?还是我的代码有问题?

I've finished coding my project, but then when I have submitted my source code in the client, it was tested, then memory leaks were detected. I have tested in Instruments using Leaks. What I am having problem with is in my AVPlayer and in my AVAudioPlayer and something in my AppDelegate. Should I find an alternate on this? or there's something wrong with my code?

下面是我的代码(顺便说一句,我正在使用ARC):

Here is my code below(I am using ARC by the way):

---> AppDelegate

int main(int argc, char *argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([RootViewAppDelegate class]));
    }
}

AND

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{  
[window makeKeyAndVisible];

---> AVPlayer

self.moviePlayer = [AVPlayer playerWithURL:[NSURL fileURLWithPath:moviePath]];

---> AVAudioPlayer

NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
resourcePath = [resourcePath stringByAppendingString:@"/Normal.wav"];
NSLog(@"Path to play: %@", resourcePath);
NSError* err;

//Initialize our player pointing to the path to our resource
BGMplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:resourcePath] error:&err];

if( err ){
    //bail!
    NSLog(@"Failed with reason: %@", [err localizedDescription]);
}
else{
    //set our delegate and begin playback
    BGMplayer.delegate = self;
    [BGMplayer play];
    BGMplayer.numberOfLoops = -1;
    BGMplayer.currentTime = 0;
    BGMplayer.volume = 1.0;
} 

这是我检测到上述情况的方法:

Here is how I detect those above:

希望有人会帮助我,这是我第一次检测到内存泄漏.所以希望您的指导.非常感谢.

Hope someone would help me, this is kinda my first time detecting memory leaks. So I hope for your guidance. THANK YOU VERY MUCH.

推荐答案

我的猜测是

//set our delegate and begin playback
BGMplayer.delegate = self;

AVPlayer保留了您的视图,并且由于您的视图还保留了AVPlayer,因此您得到了一个保留圆圈,可以防止两者都被弧释放.

AVPlayer retains your view, and since your view also retains the AVPlayer you got a retain circle that prevents both from beeing released by arc.

我建议在不再需要该委托时将其设置为nil ...可能是通过覆盖视图中的removeFromSuperview来实现的.

I'd suggest setting the delegate to nil when it is not longer needed... perhaps by overwriting removeFromSuperview in your view.

在您的视图中添加以下内容:

Add the following to your view:

- (void)removeFromSuperview {
    BGMplayer.delegate = nil;
    [super removeFromSuperview];
}

这篇关于检测/修复内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆