How to catch NSUnknownKeyException in swift 2.2?

只愿长相守 提交于 2019-12-10 18:07:08

问题


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

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

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:

How can I catch this exception?

Any help will be appreciated.


回答1:


You can't do it in Swift.

Don't confuse errors and exceptions:

  • 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.

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.




回答2:


You can catch the exception, using a Swift wrapper around Objective-C's @try/@catch, such as https://github.com/williamFalcon/SwiftTryCatch.

Usage for your situation would be:

SwiftTryCatch.try({ 
    item.setValue(field.1, forKey: field.0)

}, catch: { (exception) in
    print("Trying to set wrong value for the item ")

}, finally: {

})


来源:https://stackoverflow.com/questions/37494218/how-to-catch-nsunknownkeyexception-in-swift-2-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!