iwa*_*bed 5 iphone memory-leaks objective-c avaudioplayer
我一直在搞乱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];
}
Run Code Online (Sandbox Code Playgroud)
Cocoa 中内存管理的技巧是平衡对 的任何调用alloc,retain或copy与后续的release.
在这种情况下,您将发送alloc来初始化theAudio变量,但您永远不会发送release.
假设您一次只能播放一种声音,那么最好的方法是使用控制器上的一个属性(具有此-touchesBegan方法的控制器)。属性声明如下所示:
@property (nonatomic, retain) AVAudioPlayer * theAudio;
Run Code Online (Sandbox Code Playgroud)
然后,您需要在您的方法中theAudio设置:nilinit
theAudio = nil; // note: simple assignment is preferable in init
Run Code Online (Sandbox Code Playgroud)
并确保在您的dealloc方法中释放变量:
[theAudio release];
Run Code Online (Sandbox Code Playgroud)
现在,你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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
343 次 |
| 最近记录: |