Objective-c: How to release memory for AvAudioPlayer
I have a sound file that I use throughout my program:
NSString *soundPath1 = [[NSBundle mainBundle] pathForResource:@"mysound" ofType:@"mp3"];
NSURL *soundFile1 = [[NSURL alloc] initFileURLWithPath:soundPath1];
soundFilePlayer1 = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile1 error:nil];
[soundFilePlayer1 prepareToPlay];
So soundFilePlayer1 is defined in my .h file because I need it to be global.
Now... do I need to rele开发者_如何学Goase soundFilePlayer1 and soundFile1? (and soundPath1?)
If so... where do I do this? I think I need to release soundFilePlayer1 in: (but do I need to stop it first since it may be playing when they exit the program?)
- (void)dealloc {
[soundFilePlayer1 release];
}
what about the other files... where do I release those? Thanks
Remember a simple rule of thumb. Only release if you have called alloc
, init
, or new
on the object. So, you'll want to release soundFile1
. Alternatively, you can use a convenience method and have the sound file added to the autorelease pool automatically:
NSString *path = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"];
NSURL *file = [NSURL fileURLWithPath:path]; //autoreleased
player = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:nil];
if([player prepareToPlay]){
[player play];
}
And yes, you can release player
(soundFilePlayer1
) in dealloc
, but if you're not looping the audio file there's a better way. Conform to the AVAudioPlayerDelegate
:
@interface YourView : UIViewController <AVAudioPlayerDelegate> { //example
Then implement the method here:
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
//your audio file is done, you can release safely
[player release];
}
精彩评论