我有一个自定义的 UITableViewCell
,其中有一个 AVPlayer
。我已将观察者添加到 playerItem
以了解视频何时结束。该单元格可以获得要播放的新文件,在这种情况下,它会用新实例替换 player
和 playerItem
。以前,当我添加观察者时,我必须在 dealloc 中删除它,否则应用程序会崩溃。
这一次,我注意到即使我在删除 playerItem
之前不删除观察者,一切都正常。
为什么我不需要在这种情况下移除观察者?
@interface CallResultTableViewCell : UITableViewCell
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerItem *playerItem;
@property (nonatomic, strong) NSURL *url;
-(void) embedUrl:(NSURL *)url;
@end
-(void) embedUrl:(NSURL *)url {
if (self.url == nil || ![self.url isEqual:url]) {
if (self.player != nil) {
[self.player pause];
self.player = nil;
//[[NSNotificationCenter defaultCenter] removeObserver:self
// name:AVPlayerItemDidPlayToEndTimeNotification
// object:self.playerItem];
self.playerItem = nil;
//...
}
if (url != nil) {
self.playerItem = [myUrls playerItemWithURL:url];
self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
self.url = url;
//...
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(itemDidFinishPlaying:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:self.playerItem];
}
}
[self.player play];
}
-(void)itemDidFinishPlaying:(NSNotification *) notification {
[self.playerItem seekToTime:kCMTimeZero];
[self.player play];
}
我还在 dealloc
中调用了 remove observer
:
-(void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self
name:AVPlayerItemDidPlayToEndTimeNotification
object:self.playerItem];
}
ARC 已开启。
最佳答案
来自 Apple Developer Release Notes :
In OS X 10.11 and iOS 9.0 NSNotificationCenter and NSDistributedNotificationCenter will no longer send notifications to registered observers that may be deallocated.
这意味着您不需要从 iOS 9 或 OS X 10.11 中删除观察者。
关于ios - 我什么时候需要删除观察者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41803421/