iCoder iCoder - 1 year ago 78
Objective-C Question

AVAudioPlayer was deallocated while key value observers were still registered with it

-(void) setupAVPlayerForURL:(NSString *)url
[appdelegate.sharedplayer stop];

appdelegate.sharedplayer=[[AVAudioPlayer alloc] initWithContentsOfURL:url1 error:NULL];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

[appdelegate.sharedplayer setVolume:appdelegate.volumeDelegate];

[appdelegate.sharedplayer play];
self.seekBarSlider.minimumValue = 0.0f;
self.seekBarSlider.maximumValue = appdelegate.sharedplayer.duration;

[self loadAlbumArt];
[appdelegate.sharedplayer addObserver:self forKeyPath:@"status" options:0 context:nil];

I get this log message whenever I run this app except first time But the app is not crashing

An instance 0xc1693d0 of class AVAudioPlayer was deallocated while key value observers were still registered with it.
Observation info was leaked, and may even become mistakenly attached to some other object. Set a breakpoint on NSKVODeallocateBreak to stop here in the debugger.

Here's the current observation info:

<NSKeyValueObservationInfo 0xc194d90> (
<NSKeyValueObservance 0xc194e40: Observer: 0xc1697d0, Key path:
status, Options: <New: NO, Old: NO, Prior: NO> Context: 0x0,
Property: 0xc194d70> )

What I am doing wrong??

Answer Source

You have to remove self from the observers. When you call -stop, the instance of AVAudioPlayer gets deallocated (your creating a new one). But you'r trying to continue reserving its values.

So you try to observe an instance that does not longer exist in memory.

Try this:

- (void)setupAVPlayerForURL:(NSURL *)url {
    [[appdelegate sharedplayer] removeObserver:self];
    [[appdelegate sharedplayer] stop];

    // and so on

Your app is not crashing because your accessing the deallocated instance. Rather the system "crashes" your app because the memory address of the observed object (which is then deallocated) will probably point to some other object later, which would cause wrong observing messages to be dispatched to your observer.