5

我一直在搞乱 Leaks 试图找出哪个函数没有被释放(我对此仍然很陌生)并且可以真正使用一些经验丰富的洞察力。

我有这段代码似乎是罪魁祸首。每次我按下调用此代码的按钮时,都会额外分配 32kb 的内存给内存,并且当释放按钮时,该内存不会被释放。

我发现每次AVAudioPlayer调用播放 m4a 文件时,解析 m4a 文件的最终函数是MP4BoxParser::Initialize(),这反过来又通过分配 32kb 的内存Cached_DataSource::ReadBytes

我的问题是,我如何在完成后重新分配它,以便每次按下按钮时它不会继续分配 32kb?

非常感谢您提供的任何帮助!

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

//stop playing
theAudio.stop;


// cancel any pending handleSingleTap messages 
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(handleSingleTap) object:nil];

UITouch* touch = [[event allTouches] anyObject]; 


NSString* filename = [g_AppsList objectAtIndex: [touch view].tag];

NSString *path = [[NSBundle mainBundle] pathForResource: filename ofType:@"m4a"];  
theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];  
theAudio.delegate = self; 
[theAudio prepareToPlay];
[theAudio setNumberOfLoops:-1];
[theAudio setVolume: g_Volume];
[theAudio play];
}
4

2 回答 2

2

Cocoa 中内存管理的技巧是平衡对 的任何调用allocretaincopy与对release.

在这种情况下,您发送alloc以初始化您的theAudio变量,但您永远不会发送release.

假设您一次只能播放一种声音,最好的方法是使用控制器上的属性(具有此-touchesBegan方法的控制器)。属性声明如下所示:

@property (nonatomic, retain) AVAudioPlayer * theAudio;

然后,您需要在您的方法中设置theAudio为:nilinit

theAudio = nil; // note: simple assignment is preferable in init

并确保在您的dealloc方法中释放变量:

[theAudio release];

现在,您touchesBegan可能看起来像这样:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    //stop playing
    theAudio.stop;
    ...
    AVAudioPlayer * newAudio = [[AVAudioPlayer alloc] initWithContentsOfUrl:...];
    self.theAudio = newAudio; // it is automatically retained here...

    theAudio.delegate = self; 
    [theAudio prepareToPlay];
    [theAudio setNumberOfLoops:-1];
    [theAudio setVolume: g_Volume];
    [theAudio play];

    [newAudio release];       // ...so you can safely release it here
}
于 2010-04-14T02:50:04.817 回答
1

这条线在我看来是罪魁祸首:

theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];  

这个资源什么时候释放?

于 2010-04-14T02:49:17.533 回答