问题描述
|
- (IBAction) btnFire:(id)sender {
Nsstring *path = [Nsstring stringWithFormat:@\"%@%@\",[[NSBundle mainBundle] resourcePath],@\"/gunShot.wav\"];
NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
AVPlayer *shotSound = [[AVPlayer alloc] initWithURL:filePath];
[shotSound play];
}
如果我在这里释放shotSound,它将不会播放。同时没有泄漏。
为什么仪器显示无泄漏?如何释放shotSound?
解决方法
因为当您按下按钮时会一次又一次地需要声音,而不是每次都应该在类级别上声明它而不是在按钮中初始化它,或者可以在viewDidLoad方法中将其初始化,或者也可以这样做
- (IBAction) btnFire:(id)sender {
if(shotSound==nil)
{
NSString *path = [NSString stringWithFormat:@\"%@%@\",[[NSBundle mainBundle] resourcePath],@\"/gunShot.wav\"];
NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
shotSound = [[AVPlayer alloc] initWithURL:filePath];
}
[shotSound play];
}
用dealloc
将其释放。如果您只想在此操作上有声音,可以使用AVAudioPlayer
。
有时仪器的泄漏无法检测到,在这种情况下,您可以使用构建和分析工具。另外,正如您所说的,如果释放播放器对象,则应用崩溃可能是因为音频仍在播放并且您释放了播放器(不确定)。
,你可以试试
AVPlayer *shotSound = [AVPlayer playerWithURL:filePath];
注意:这将返回一个新播放器,以播放由给定URL引用的单个视听资源。