2011-04-14 181 views
2
- (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?

回答

0

您可以嘗試

AVPlayer *shotSound = [AVPlayer playerWithURL:filePath];

注:這將返回一個新的播放器來播放由給定的URL引用一個單一的視聽資源。

+0

這樣有什麼缺點嗎? – Michael 2011-04-14 08:16:30

+0

如果你只想播放一個文件,我認爲這就足夠了。當你這樣做時,當AutoReleasePool排空時,玩家獲得釋放 – visakh7 2011-04-14 09:31:21

2

如您在按下按鈕等等,而不是initiliazing它在按鈕每次應在類級別聲明它,要麼你可以在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

有時儀器的泄漏無法檢測到,在這種情況下,您可以使用構建和分析工具。此外,正如你所說,如果你釋放播放器對象,那麼應用程序崩潰可能會導致音頻仍在播放,並且你釋放播放器(不確定)。

+0

讓我知道是誰給了我低調,爲什麼? – Jhaliya 2011-04-14 08:13:57

+0

這是正確的答案。 'shotSound'應該被分配一次,然後在'dealloc'和'viewDidUnload'中釋放。我添加了'viewDidUnload',因爲當視圖不存在時沒有理由保持分配。 @ Ravin的代碼將在需要時重新初始化它。 – XJones 2011-04-14 08:19:07

+0

謝謝。你的意思是shotSound應該是伊娃嗎? – Michael 2011-04-14 08:30:14

相關問題