gpt4 book ai didi

ios - 在 Swift 中处理未捕获的异常 valueForUndefinedKey

转载 作者:搜寻专家 更新时间:2023-10-31 08:06:07 25 4
gpt4 key购买 nike

我有一个第三方库类,它的源代码不对我开放。例如像这样:

class MyClass: NSObject {
let myProperty = 10
}

我可以像这样获取 myProperty 值。

let test = MyClass().value(forKey: "myProperty")  // 10

我想检查 myProperty 是否存在于 MyClass 中。原因是我不希望我的应用程序在 3rd 方类实现将来发生变化时崩溃。

为了测试我试过了

guard let test = MyClass().value(forKey: "myProperty1") else { return }  // crash

if let test = MyClass().value(forKey: "myProperty1") { }  // crash

do {
let test = try MyClass().value(forKey: "myProperty1") // crash
} catch { }

我在各方面都崩溃了。

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__lldb_expr_80.MyClass 0x608000223a00> valueForUndefinedKey:]: this class is not key value coding-compliant for the key myProperty1.'

最佳答案

当为未定义的键调用 valueForKey: 时,the runtime forwards the callvalueForUndefinedKey:。后者的默认实现只是引发 NSUndefinedKeyException

我们无法从 Swift 代码中捕获异常,但我们可以在扩展中覆盖方法 valueForUndefinedKey: 并返回一些错误:

extension NSObject {
@objc
func value(forUndefinedKey key: String) -> Any {
NSError(domain: "Dynamic", code: 404, userInfo: [NSLocalizedDescriptionKey: "Accessing undefined key: '\(key)'"])
}
}

关于ios - 在 Swift 中处理未捕获的异常 valueForUndefinedKey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41328001/

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