Leo
Leo

Reputation: 865

How to set AVPlayerItem to nil when observer does not complete

I add a observer named 'status' into AVPlayerItem. Send the observer then set AVPlayerItem to nil when the observer does not complete

I have remove the observer when dealloc AVPlayerItem

Get the following error:

NSInternalInconsistencyException', reason: 'An instance 0x7dc5e7d0 of class AVPlayerItem was deallocated while key value observers were still registered with it. Current observation info: ( Context: 0x0, Property: 0x7b8ad140>

Upvotes: 0

Views: 1533

Answers (3)

Leo
Leo

Reputation: 865

It caused initial the avplayeritem by async

Upvotes: 0

Clay Garrett
Clay Garrett

Reputation: 1023

Before you set the playerItem to nil, remove the observer:

playerItem.removeObserver(self, forKeyPath: "status")

If you wait until deinit/dealloc, after you've already set the playerItem to nil, then you won't have a reference to it anymore to remove the observers.

Upvotes: 0

prolfe
prolfe

Reputation: 1354

I don't believe the AVPlayerItem should be observing anything, it's hard to say in your case without a concrete example. Generally the flow for this would be that your controller be an observer on some notification from the AVPlayerItem.

For example:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(movieItemDidReachEnd:)
                                             name:AVPlayerItemDidPlayToEndTimeNotification
                                           object:nil];

Then when you're done (i.e. when you are setting the AVPlayerItem to nil), you remove the observer:

[[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];

If you provide more detail, maybe I can help more. Thanks!

Edit:

In swift it would be...

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "movieDidReachEnd", name: AVPlayerItemDidPlayToEndTimeNotification, object: nil)

    NSNotificationCenter.defaultCenter().removeObserver(self, name: AVPlayerItemDidPlayToEndTimeNotification, object: nil)

Upvotes: 1

Related Questions