AVAudioPlayer内存泄漏 [英] AVAudioPlayer memory leak

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

问题描述

我必须在iphone卡游戏循环播放一个whoosh声音,我使用下面仍然有内存泄漏。
还可以做些什么来避免泄漏?

I have to play a whoosh sound in an iphone card game loop and I am using the below that still has a memory leak. What else can be done to avoid the leak?

// AVAudioPlayer ------------------ -------------------------------------------------- -------------

// AVAudioPlayer ---------------------------------------------------------------------------------

    NSAutoreleasePool *audioDataspool = [[NSAutoreleasePool alloc] init]; // pool is created
{
    NSString *soundpath = [[NSBundle mainBundle] pathForResource:@"cardwhoosh" ofType:@"mp3"];

    NSData *audioData = [[NSData dataWithContentsOfFile:soundpath]autorelease];

    AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithData:audioData error:NULL];

    soundpath   = nil;
    [soundpath release];

    [player play];//play sound

    player  = nil;
    [player release];
    [player autorelease];
    audioData   = nil;
    [audioData release];
}
    [audioDataspool release]; // all your autoreleased objects are released


推荐答案

t认为你理解内存管理。请阅读Apple的文档或其他有关此主题的教程,以获得进一步的帮助。

I don't think you understand memory management at all. Please read Apple's documentation or other tutorials on this subject for further help.

以下源代码将无泄漏地工作:

The below source code will work without leaks:

NSString *soundpath = [[NSBundle mainBundle] pathForResource:@"cardwhoosh" ofType:@"mp3"]; /* autoreleased object */
NSData *audioData = [NSData dataWithContentsOfFile:soundpath]; /* autoreleased object */
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:audioData error:NULL]; /* contains init, so must be released */
[player play];
[player release], player = nil; /* Setting to nil is optional */

这里所有的变量都是指针。在Objective-C中,所有包含 init create copy的方法返回不会自动释放的对象。在你的情况下,这意味着只有 player 需要被释放。这可以通过发送它 autorelease 来完成,然后它会被抛出在runloop的 NSAutoreleasePool 的runloop。或者,您可以发送 release 立即发布。

All the variables you have here are pointers. In Objective-C, all methods containing init, create and copy return objects that won't get autoreleased. In your case this means that only player needs to be released. This can either be done by sending it autorelease, it will then be thrown on the runloop's NSAutoreleasePool and released at the end of the runloop. Or you could release it immediately by sending release, which I've done above.

即使在您调用 release 之前,变量仍然为 nil 。这意味着你然后调用一个 nil 指针的方法,这将什么也不做。您没有指向该对象的指针(它已被覆盖)导致内存泄漏。

You're setting your variable to nil even before you've called release. This means that you're then calling a method on a nil pointer, which will do nothing. You don't have the pointer to the object anymore (it has just been overridden) causing a memory leak.

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

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