AVPlayer消除Swift 2.2中的观察器崩溃 [英] AVPlayer removing observer crash in Swift 2.2

查看:147
本文介绍了AVPlayer消除Swift 2.2中的观察器崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个视频应用程序,它是在Swift 1中构建的,而我一直在尝试迁移到Swift 2.2.这一切(最终)都与怪异的崩溃无关,与观察者有关.

I have a video app that I built a while back in Swift 1 and I've been trying to migrate to Swift 2.2. It all (finally) works apart from a weird crash to do with observers.

func removeObservers()
{
    print("REMOVING OBSERVERS")
    if ( !self.is_image && self.player != nil  ) {
        if (self.player?.observationInfo != nil) {

            self.player?.removeObserver(self, forKeyPath: "currentItem.status")
            self.player?.removeObserver(self, forKeyPath: "readyForDisplay")

        }
    }
    NSNotificationCenter.defaultCenter().removeObserver(self)

}

这以前使用SwiftTryCatch起作用,但是行与'不能从键名"readyForDisplay"中删除观察者,因为它没有注册为观察者而无法删除.""如果我将其释放,则释放对象.

This worked previously using SwiftTryCatch but with the lines in place crashes with "'Cannot remove an observer for the key path "readyForDisplay" from because it is not registered as an observer.'" OR with that an observer is registered on a deallocated object if I comment it out.

如果我向其中添加一个do {} catch {},则会收到错误消息"this not throw",并且将其崩溃.我该如何将其放入尝试捕获格式?

If I add a do { } catch {} to it I get an error that "this does not throw" and it just crashes the same. How do I go about putting this in some form of try-catch format?

推荐答案

在Swift 2中,libs对真正出乎意料的错误(抛出)与程序员可以防止的错误(执行不是抛出,而是只是使您的应用崩溃了.

In Swift 2, the libs got annoyingly strict about errors that are truly unexpected (which throw) versus errors that the programmer could have prevented (which do not throw, but just crash your app).

(我不是这种区别的拥护者,或者至少不是苹果做出的关于哪个错误属于哪个类别的所有特定决策的支持者.JSONAPI在该部门毫无根据.但是……我们与我们有API.)

(I’m not a fan of this distinction, or at least not of all the specific decisions Apple made about which errors fall in which category. The JSON API verges on the nonsensical in this department. But…we work with the API we’ve got.)

NSKeyValueObserving文档说:

如果对象尚未注册为观察者,则调用removeObserver:forKeyPath:是错误的.

这是一个错误"是Apple代码,您有责任永远不要这样做,如果这样做,您的应用程序将以无法捕获的方式崩溃."

"It is an error" is Apple code for "you are responsible for never doing this, and if you do, your app will crash in an uncatchable way."

在这种情况下,通常可以执行一个API调用来检查您将要执行的操作的有效性.但是,对于AFAIK,您没有可以调用的KVO API,"X是否正在观察对象Z的关键路径Y?"这意味着您有三个选择:

In these situations, there is usually an API call you can make to check the validity of the thing you’re about to do. However, AFAIK, there’s no KVO API call you can make to ask, "Is X observing key path Y of object Z?" That means you have three options:

  • 弄清楚为什么要尝试从您未观察的对象中删除观察者,并使用程序自己的内部逻辑来阻止观察者.
  • 为我正在观察的玩家"保留一个弱实例变量,并在尝试删除观察者之前检查其是否匹配.
  • 将自身添加为观察者,然后再将其移除. (我很确定可以添加多余的内容.)

这篇关于AVPlayer消除Swift 2.2中的观察器崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆