在Swift中捕捉Objective-C异常 [英] Catch Objective-C exception in Swift
问题描述
我试图使用 obj.setValue(value,forKey:key)设置Swift代码中的
。 @objc
对象的值
I am trying to set the value of an @objc
object in my Swift code using obj.setValue(value, forKey: key)
.
当对象的属性被设置时,它工作正常。但是如果没有,我的应用程序会因为未知的 NSException
(class is not key value coding-compliant ...)崩溃。
It works fine when the object has the property being set. But if it doesn't, my app crashes hard with an uncaught NSException
("class is not key value coding-compliant…").
如何在Objective-C中捕获和吸收这个异常,以免崩溃我的应用程序?我尝试将其包装在Swift try-catch中,但是它抱怨说没有任何指令会抛出任何东西。
How can I catch and absorb this exception like I can in Objective-C so as to not crash my app? I tried wrapping it in a Swift try-catch, but it complains that none of the instructions throws and does nothing.
推荐答案
此回答:
//
// ExceptionCatcher.h
//
#import <Foundation/Foundation.h>
NS_INLINE NSException * _Nullable tryBlock(void(^_Nonnull tryBlock)(void)) {
@try {
tryBlock();
}
@catch (NSException *exception) {
return exception;
}
return nil;
}
这篇关于在Swift中捕捉Objective-C异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!