Dmytro
Dmytro

Reputation: 839

Do I need to release before next alloc?

I have a memory management question. I am using a single instance of AVAudioPlayer in a singleton pattern to play multiple audio files. I have multiple views which have Play buttons, and when a user comes to a view and presses that button, a global instance of AVAudioPlayer gets called, and is instantiated with a new mp3 file:

NSURL *audioFileLocationURL = [[NSBundle mainBundle] URLForResource:audioFile withExtension:fileExtension];
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileLocationURL error:&error];

Now, before I do this for the second time, third, and n-th time, do I need to release the previous allocation? Maybe set it to nil?? All I'm trying to do here is to prevent memory leaks.

Before you ask: Yes, I know about AVQueuePlayer, and no, I can't use it in this particular case.

Upvotes: 0

Views: 98

Answers (2)

Ken Thomases
Ken Thomases

Reputation: 90541

Since you are assigning to a property (self.audioPlayer), you don't need to release in the code you showed.

Ideally, all memory management should be done in the property's accessors. The setter would release the old value and retain (or, for a property with the copy attribute, copy) the new value. The getter might just return the value with no memory management, but an atomic property will likely retain and autorelease the value before returning it.

This, of course, assumes that the property was declared strong, as it should have been.

Upvotes: 3

Bienemann
Bienemann

Reputation: 152

If you are not using ARC you should be releasing and setting it to nil.

if (self.audioPlayer){
     [_audioPlayer release], _audioPlayer = nil;
}
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileLocationURL error:&error];

Upvotes: 0

Related Questions