NSError.setUserInfoValueProvider(forDomain:provider:)
在 MacOS 10.11/iOS 9 中引入,作为使用 block 填充给定错误域的 NSError
的 userInfo
字典的方法,从而避免大量样板和重复在可能会抛出异常的代码中。
我尝试像这样使用它:
if NSError.userInfoValueProvider(forDomain: "Test") == nil {
NSError.setUserInfoValueProvider(forDomain: "Test"){ err, userInfoKey in
print("This is an error:", err, userInfoKey)
return nil
}
}
调用站点如下所示:
throw NSError(domain: "Test", code: 0, userInfo: nil)
抛出错误时,日志中会填充“这是一个错误:”,但错误本身或 userInfoKey
永远不会打印出来。程序最终中止,并在日志中显示最终消息:
warning: could not execute support code to read Objective-C class data in the process. This may reduce the quality of type information available.
最佳答案
问题是在
中打印err
print("This is an error:", err, userInfoKey)
递归地调用相同的值提供程序,因为错误的字符串表示形式是确定的。程序最终因堆栈溢出而崩溃。您可以通过在该行设置断点来验证这一点。
如果将行更改为
print("This is an error:", userInfoKey)
然后一切都会按预期进行。
关于swift - NSError.setUserInfoValueProvider 无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53067321/