AVAudioPlayer内存泄漏

时间:2011-04-24 16:38:02

标签: iphone objective-c cocoa-touch

我必须在iphone卡游戏循环中播放嗖嗖声,我使用的是仍有内存泄漏的情况。 还有什么办法可以避免泄漏?

// 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

1 个答案:

答案 0 :(得分:4)

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

以下源代码无泄漏:

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中,包含initcreatecopy的所有方法都会返回不会自动释放的对象。在您的情况下,这意味着只需要释放player。这可以通过发送它autorelease来完成,然后它将被抛出到runloop的NSAutoreleasePool并在runloop结束时释放。或者您可以通过发送release立即释放它,我已在上面做过。

您甚至在调用nil之前就已将变量设置为release。这意味着您正在调用nil指针上的方法,该指针将不执行任何操作。你没有指向对象的指针(它刚被覆盖)导致内存泄漏。