ios - 我什么时候需要删除观察者

标签 ios objective-c

我有一个自定义的 UITableViewCell,其中有一个 AVPlayer。我已将观察者添加到 playerItem 以了解视频何时结束。该单元格可以获得要播放的新文件,在这种情况下,它会用新实例替换 playerplayerItem。以前,当我添加观察者时,我必须在 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/

相关文章:

ios - 在仅在最后一个 UIImageview 上可见的 PageViewController 上添加 UIButton

ios - UITableViewCell 中的自动布局约束不匹配

objective-c - 将 performSelector 与三个或更多参数一起使用?

objective-c - 在 Xcode 6 中关闭指定初始化程序检查

iphone - "_OBJC_CLASS_$_CATransaction, referenced from:"编译时错误是什么意思?

php - 如何在 android 推送通知中显示来自链接的图像?

ios - 二进制表达式 ('NSString *' 和 'NSString *' 的无效操作数)

android - 钛未捕获错误: no such table

ios - 用颜色填充 CGBitmapContext

iphone - iOS 应用程序的启动顺序是什么?