AVAudioPlayer memory leak

前端 未结 1 1447
星月不相逢
星月不相逢 2021-01-16 17:02

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

1条回答
  •  太阳男子
    2021-01-16 17:49

    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.

    0 讨论(0)
提交回复
热议问题