2017-01-23 128 views
0

我有一个自定义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]; 
} 

我也呼吁remove observerdealloc

-(void)dealloc 
{ 
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                name:AVPlayerItemDidPlayToEndTimeNotification 
                object:self.playerItem]; 
} 

ARC被打开。

回答

4

从苹果开发者发布Notes

在OS X 10.11和iOS 9.0 NSNotificationCenter和NSDistributedNotificationCenter将不再发送通知可能被释放注册的观察员。

这意味着你不需要从iOS 9或OS X 10.11中删除观察者。

1

你应该在dealloc中删除。

- (void)dealloc { 
    [super dealloc]; 
    //add remove observer code 
} 
+0

我也在dealloc中看到它,请参阅编辑,但为什么我不需要每次删除它时都要删除我正在观察的对象? – SIMEL

+0

之前ios 9意味着在ios8它崩溃,因为它试图发送消息后也释放,但在ios9如果资源未找到它自动removeObserver。 –

+0

那么我需要将embedUrl中的remove删除吗? – SIMEL

0

如果您确定,视图控制器将弹出,然后删除观察者。

override func viewWillDisappear(animated: Bool) 
{ 
    super.viewWillDisappear(animated) 
    if self.isMovingFromParentViewController() 
    { 
     //View controller was popped 
     //Remove any observer. 
    } 
}