2011-11-08 177 views
0

不知道這是一個模擬器的問題,或者我失去了一些東西,下面的代碼給我一個內存泄漏,雖然音頻是在dealloc中發佈的。我正在播放.wav文件,並且聲音將根據整數的值而改變。該應用運行確定,但我whwn測試此在xcode中AVAudioPlayer導致內存泄漏

任何建議非常感謝16位泄漏被判:

#import <UIKit/UIKit.h> 
#import <AVFoundation/AVFoundation.h> 

@interface Water : UIViewController 
<AVAudioPlayerDelegate> 

{ 

} 

@property (nonatomic,retain) AVAudioPlayer *theAudio; 


-(IBAction) goButMenu: (id) sender; 
-(IBAction) goDrinkMenu: (id) sender; 
-(IBAction) playwater; 


@end 



@implementation Water 
@synthesize theAudio; 

-(IBAction) goDrinkMenu: (id) sender{ 

ButDrinkMenu *butdrinkmenu1 = [[ButDrinkMenu alloc] initWithNibName:nil bundle:nil]; 
[self presentModalViewController:butdrinkmenu1 animated:YES]; 

} 

-(void) viewDidLoad { 

if (BoyOrGirl == 1) { 

    NSString *path = [[NSBundle mainBundle] pathForResource:@"Applause" ofType:@"wav"]; 
    theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 
    theAudio.delegate = self; 
    [theAudio play]; 


} 

else { 
    NSString *path = [[NSBundle mainBundle] pathForResource:@"bongo" ofType:@"wav"]; 

    theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 
    theAudio.delegate = self; 
    [theAudio play]; 

} 





} 

-(IBAction) playwater{ 

if (BoyOrGirl == 1) { 

    NSString *path = [[NSBundle mainBundle] pathForResource:@"Applause" ofType:@"wav"]; 
    theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 
    theAudio.delegate = self; 
    [theAudio play]; 




} 

else { 
    NSString *path = [[NSBundle mainBundle] pathForResource:@"bongo" ofType:@"wav"]; 
    theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 
    theAudio.delegate = self; 
    [theAudio play]; 

} 


} 

回答

0

直接在設備上絕對測試;用模擬器測試泄漏可能會返回不準確的結果。

這就是說,這個代碼示例有幾個與內存有關的問題。你可能希望在這裏包含你的dealloc方法,因爲這可能會提供一些見解,但是這裏有一個問題(出現在你的幾個分配中):

你的AVAudioPlayer沒有被分配給你的屬性,也沒有被釋放在適用範圍。理想情況下,球員分配將看起來更像:

AVAudioPlayer *myPlayer = [[AVAudioPlayer alloc] initWithContents.... 
[myPlayer setDelegate:self]; 
[self setTheAudio:myPlayer]; 
[myPlayer release]; 

至於反對你如何實現它,這賦予玩家直接實例變量:

theAudio = [[AVAudioPlayer alloc] initWith... 

因爲你直接分配玩家到你實例變量,您的播放器不被保留。這可能會導致提前釋放和懸掛指針,如果您試圖平衡您的呼叫,否則會導致泄漏。

+0

謝謝你,我做了一個快速測試,這段代碼解決了泄漏問題,我需要做更多的測試,但看起來不錯。乾杯。 – TJ15

+0

太棒了!如果答案有效,請選擇已接受的答案。 – isaac