我一直在与 Leaks 打交道,试图找出哪个函数没有被释放(我对此还是个新手)并且真的可以使用一些有经验的洞察力。
我有这段代码似乎是罪魁祸首。每次我按下调用此代码的按钮时,都会额外分配 32kb 的内存给内存,当释放按钮时,内存不会被释放。
我发现每次调用 AVAudioPlayer
播放 m4a 文件时,解析 m4a 文件的最终函数是 MP4BoxParser::Initialize()
而这个依次通过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];
}
最佳答案
Cocoa 中内存管理的诀窍是平衡任何对 alloc
、retain
或 copy
的调用与对 的后续调用>发布
。
在这种情况下,您将发送 alloc
来初始化您的 theAudio
变量,但您永远不会发送 release
。
假设您一次只播放一种声音,最好的方法是在您的 Controller 上设置一个属性(具有此 -touchesBegan
方法的 Controller )。属性声明如下所示:
@property (nonatomic, retain) AVAudioPlayer * theAudio;
然后您需要在 init
方法中将 theAudio
设置为 nil
:
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
}
关于iphone - 如何找到加载到 Malloc 32kb 中的漏水水龙头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2634523/