gpt4 book ai didi

ios - removeObserver:forKeyPath:在keyPath通知期间崩溃

转载 作者:行者123 更新时间:2023-12-01 16:08:51 29 4
gpt4 key购买 nike

我创建了一个观察器来跟踪AVPlayer的“速率”。每当AVPlayer速率按预期变化时,都会显示观察者通知。但是,当我尝试在AVPlayer正在播放的项目上结束播放时删除观察者时,出现以下崩溃:

*** Terminating app due to uncaught exception 'NSRangeException', reason: 'Cannot remove an observer <MediaController 0x10181e000> for the key path "rate" from <NSNotificationCenter 0x1740da080> because it is not registered as an observer.'

这没有任何意义,因为必须注册观察者才能删除我的观察者。换句话说,我删除观察者的时间点是在处理程序中,用于接收观察者通知。显然,观察者已注册。这是我创建观察者的相关代码:
 AVPlayerItem *item = [[AVPlayerItem alloc]initWithURL:address];
moviePlayer = [[AVPlayer alloc]initWithPlayerItem:item];

[moviePlayer addObserver:self
forKeyPath:@"rate"
options:NSKeyValueObservingOptionNew
context:NULL];

然后,当正在播放的项目结束时,在收到观察者通知时执行以下处理程序代码:
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

if ([keyPath isEqualToString:@"rate"]) {
float rate = [change[NSKeyValueChangeNewKey] floatValue];
if (rate == 0.0) {
// Playback stopped

if (CMTimeGetSeconds(moviePlayer.currentTime) >=
CMTimeGetSeconds(moviePlayer.currentItem.duration)) {
// Playback reached end

// Remove further notifications until the next time we need the movie player
[[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:@"rate"];

在执行removeObserver时,应用程序崩溃。我也尝试过添加&moviePlayer的非空上下文,并使用该上下文删除观察者,但是它仍然崩溃。我也尝试过延迟删除,但这也不能解决问题。

为避免此崩溃,我缺少什么?

最佳答案

您没有向NSNotificationCenter注册观察者,而是向moviePlayer对象注册。

尝试做:

// Remove further notifications until the next time we need the movie player
[moviePlayer removeObserver:self forKeyPath:@"rate"];

关于ios - removeObserver:forKeyPath:在keyPath通知期间崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42473059/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com