当前位置: 动力学知识库 > 问答 > 编程问答 >

Memory Management Help with Sounds being played - iPhone Programmingv

问题描述:

I'm beginning iPhone programming and I am trying to make a little test app which plays a sound when you press a button. This question is pretty noob so bear with me. Pretty much I'm trying to figure out how to handle the memory situation. Where do I release the instances created so as to avoid memory issues? Right now if I click on the button multiple times quickly the app crashes. I tried declaring everything in viewDidLoad and putting the release in the dealloc method, but under this design I have to wait until the entire sound is done playing before being able to play the sound again. I want to be able to press the button in the middle of a sound being played and "interrupt it" if that makes sense.

The way its written now is when you press a button, this method is called and the sound is played

-(IBAction)buttonPressed:(id)sender{

NSString *path = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"mp3"];

AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error: NULL];

theAudio.delegate = self;

[theAudio play];

}

In this set up it works so that I can "interrupt" an already playing sound by pressing the button again and the sound restarts. However pressing it quickly makes the app crash.

网友答案:

You should release immediately before you exit the method like so:

-(IBAction)buttonPressed:(id)sender{
 NSString *path = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"mp3"];
 AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error: NULL];
 theAudio.delegate = self;
 [theAudio play];
 [theAudio release];
    }

or something like that.

Because when you alloc/init a local variable you assign it a retain count of +1. But when you exit the method the reference to that var is still living and you can't access it, which leads in memory leaking. Try to begin from: Memory Management. Good luck.

分享给朋友:
您可能感兴趣的文章:
随机阅读: