Reputation: 2381
I use the following line to add an observer:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidFinishPlaying) name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
My observer (self
) will never be deallocated.
But when the user starts playing a different item, the old self.playerItem
will be deallocated---but will always be replaced with a new one, which I want to continue observing.
When that happens, what happens in regards to my observer's status as an observer? Do I need to do something to stop observing the deallocated object, as is required with KVO? Or will I continue observing the new object at self.playerItem
? Or will my observer automatically be "unregistered?"
If I need to remove the observer, I wonder why there's no corresponding removeObserver
method that enables one to specify a selector; it seems I can remove an observer only wholesale via removeObserver:(id)notificationObserver
.
Upvotes: 1
Views: 991
Reputation: 3322
Since iOS 9 it is no longer needed to remove an observer from an object:
In OS X 10.11 and iOS 9.0 NSNotificationCenter and NSDistributedNotificationCenter will no longer send notifications to registered observers that may be deallocated.
However, block based observers need to be un-registered as before:
Block based observers via the -[NSNotificationCenter addObserverForName:object:queue:usingBlock] method still need to be un-registered when no longer in use since the system still holds a strong reference to these observers.
More information can be found here:
Upvotes: 3
Reputation: 2856
According to the NSNotificationCenter
class reference:
Be sure to invoke removeObserver: or removeObserver:name:object: before notificationObserver or any object specified in addObserver:selector:name:object: is deallocated.
So: you should unregister your observer before self.playerItem
deallocated.
But when the user starts playing a different item, the old self.playerItem will be deallocated---but will always be replaced with a new one, which I want to continue observing.
You may pass nil
as the last parameter of addObserver:selector:name:object:
method:
Adds an entry to the receiver’s dispatch table with an observer, a notification selector and optional criteria: notification name and sender. If you don't specify
If you pass nil, the notification center doesn’t use a notification’s sender to decide whether to deliver it to the observer.
So you will receive notification AVPlayerItemDidPlayToEndTimeNotification
from any object that posts it.
Upvotes: 3