如何在下面的代码中释放AVAudioPlayer

| 我想释放为AVAudioPlayer分配的内存,但是当我尝试释放它时,声音却没有播放,这是潜在的内存泄漏,我该如何解决。 在这里,当选择错误时使用下面的代码,然后我播放错误声音,如果我选择了多次错误选择,那么它被分配了多次,那么我该如何摆脱这种情况。
        else
        {
            NSString *soundName=@\"Error.mp3\";

            NSError *error;
            NSURL *urlString = [NSURL fileURLWithPath:[NSString stringWithFormat:@\"%@/%s\", [[NSBundle mainBundle] resourcePath],[soundName UTF8String]]];

            AVAudioPlayer *worngAudioPlay = [[AVAudioPlayer alloc] initWithContentsOfURL:urlString error:&error];// here I also used to release using autorelease then not played sound

            worngAudioPlay.delegate = self;

            if (worngAudioPlay == nil)
            {
            }
            else
            { 
                [worngAudioPlay play];
            }
            // [worngAudioPlay release]; // Here I released then not played sound
        }
谢谢, 玛丹·莫汉(Madan Mohan)。     
已邀请:
您可以在名为audioDidFinishPlaying的avaudio播放器委托方法中释放。我不知道确切的名字。但是你可能会知道我在说什么     
使它成为您的类的保留属性,然后在dealloc中释放它。 在头文件中:
@property(retain)AVAudioPlayer *player;
在您的实现(.m)文件中:
@synthesize player;
在上面的代码中:
else
{
    NSString *soundName=@\"Error.mp3\";

    NSError *error;
    NSURL *urlString = [NSURL fileURLWithPath:[NSString stringWithFormat:@\"%@/%s\", [[NSBundle mainBundle] resourcePath],[soundName UTF8String]]];

    AVAudioPlayer *worngAudioPlay = [[AVAudioPlayer alloc] initWithContentsOfURL:urlString error:&error];

    if (worngAudioPlay != nil)
    {
        // this will cause the previous one to be released
        [self setPlayer:worngAudioPlay];
        [worngAudioPlay release];
        worngAudioPlay.delegate = self;
        [worngAudioPlay play];
    }
}
在您的dealloc中:
-(void)dealloc {
    [player release];
    [super dealloc];
}
    

要回复问题请先登录注册