【问题标题】:Detecting/Fixing Memory Leaks检测/修复内存泄漏
【发布时间】:2012-09-16 20:45:44
【问题描述】:

我已经完成了我的项目的编码,但是当我在客户端提交我的源代码时,它已经过测试,然后检测到内存泄漏。我已经在Instruments using Leaks 进行了测试。 我遇到的问题是在我的AVPlayer 和我的AVAudioPlayer 以及我的AppDelegate 中。 我应该为此找到替代品吗?还是我的代码有问题?

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

--->AppDelegate

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

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

以下是我如何检测上述内容:


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

【问题讨论】:

  • 你能显示更多代码吗?我想看看你是否在不再使用对象时将引用设置为 nil。
  • 按照其他人的建议,试试 Xcode 的静态代码分析器。另一个好主意是 Instruments 的保留周期检测器:stackoverflow.com/questions/8852451/…
  • 是的,我使用过静态分析器。但我不知道为什么它没有出现。
  • @RamyAlZuhouri 想看什么代码?上面提到的类的代码
  • 你试过在 removeFromSuperview 方法中将代理设置为 nil 吗?

标签: iphone objective-c ios xcode


【解决方案1】:

首先你应该通过 shift+Command+B 组合键来分析你的代码,希望它能告诉你内存泄漏。

【讨论】:

    【解决方案2】:

    我的猜测是

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

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

    我建议在不再需要代理时将其设置为 nil...也许通过在您的视图中覆盖 removeFromSuperview

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

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

    【讨论】:

    • viewDidDisappear? moviePlayer 怎么样?
    • 如何覆盖removeFromSuperview
    • ok .. 仅适用于 UIView,不适用于 UIViewController。为什么首先需要设置委托?如果不需要,可以尝试不使用 BGMplayer.delegate = self 行。
    【解决方案3】:

    您的某些实例变量似乎没有被释放。我认为,您的 moviePlayer 属性保留了 AVPlayer 对象,而您没有在 dealloc 中释放它(可能是其他一些实例变量)。希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-07-16
      • 2012-01-12
      • 1970-01-01
      • 1970-01-01
      • 2013-07-29
      • 2017-07-29
      相关资源
      最近更新 更多