如何在Swift 2.2中捕获NSUnknownKeyException? [英] How to catch NSUnknownKeyException in swift 2.2?

查看:79
本文介绍了如何在Swift 2.2中捕获NSUnknownKeyException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要在其中设置键值的代码,如下所示:

I have a code where I want to set value for key as following:

item.setValue(field.1, forKey: field.0)

我想知道是否抛出了NSUnknownKeyException,但是我有以下内容代码并且不起作用:

and I want to catch if the NSUnknownKeyException is thrown but I have the following code and it is not working:

 do {
     try item.setValue(field.1, forKey: field.0)
 } catch _ {
     print("Trying to set wrong value for the item ")
 }

密钥无效时显示的错误如下:

The displayed error when it is a not valid key is the following:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: setValue:forUndefinedKey:

如何捕获此异常?

任何帮助将不胜感激。

推荐答案

您不能

不要混淆错误和异常:


  • 在Swift中出现错误的想法是尽早退出当前范围。

  • The idea of an error in Swift is to exit out of the current scope early.

在可可粉中出现例外的想法是,您死在水中;您永远都不应该允许这种情况发生。

The idea of an exception in Cocoa is that you are dead in the water; you should never have permitted this to happen.

现在,确实发生了可可有时会引发异常并捕获它的情况。本身。但是,如今,这种行为在官方上已被劝阻,这不是您在Swift中可以做的事情。如果您要发送的类是您自己的类,则可以根据需要实现 setValue:forUndefinedKey:,但是如果发生了未捕获的NSException,那么这就是游戏的结尾了-而Swift无法捕获它。

Now, it does happen that Cocoa sometimes throws an exception and catches it, itself. But such behavior is officially discouraged nowadays, and it is not something you can do in Swift. If the class you are sending this to is yours, you can implement setValue:forUndefinedKey: as you please, but if an uncaught NSException happens that's the end of the game — and Swift cannot catch it.

这篇关于如何在Swift 2.2中捕获NSUnknownKeyException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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