I have to play a whoosh sound in an iphone card game loop and I am using the below that still has a memory leak. What else can be done to avoid the leak?
// AVAudio
I don't think you understand memory management at all. Please read Apple's documentation or other tutorials on this subject for further help.
The below source code will work without leaks:
NSString *soundpath = [[NSBundle mainBundle] pathForResource:@"cardwhoosh" ofType:@"mp3"]; /* autoreleased object */
NSData *audioData = [NSData dataWithContentsOfFile:soundpath]; /* autoreleased object */
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:audioData error:NULL]; /* contains init, so must be released */
[player play];
[player release], player = nil; /* Setting to nil is optional */
All the variables you have here are pointers. In Objective-C, all methods containing init
, create
and copy
return objects that won't get autoreleased. In your case this means that only player
needs to be released. This can either be done by sending it autorelease
, it will then be thrown on the runloop's NSAutoreleasePool
and released at the end of the runloop. Or you could release it immediately by sending release
, which I've done above.
You're setting your variable to nil
even before you've called release
. This means that you're then calling a method on a nil
pointer, which will do nothing. You don't have the pointer to the object anymore (it has just been overridden) causing a memory leak.