【发布时间】:2019-06-13 11:17:19
【问题描述】:
我正在尝试在我的项目中使用全局错误处理,如下所示:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
NSSetUncaughtExceptionHandler { (exception) in
print(exception)
let myView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
let errorLabel :UILabel = UILabel(frame: CGRect(x: 10, y: (UIScreen.main.bounds.height/2) - 25 , width: UIScreen.main.bounds.width - 20 , height: 50))
errorLabel.text = "Exception"
myView.addSubview(errorLabel)
self.window?.addSubview(myView)
}
return true
}
但我在编码时收到此错误:
C 函数指针不能由捕获的闭包构成 上下文。
我搜索了很多,但找不到任何答案。还有什么我需要做的吗?
更新:
我发现问题在于我在块内声明变量。发生异常时我应该如何处理显示视图?
【问题讨论】:
-
您的代码可以编译(如果添加了缺少的右括号)。我认为闭包中有更多内容,这会导致问题。 – 比较stackoverflow.com/q/33260808/1187415。
-
@MartinR 我的原始代码中没有缺少括号,很抱歉在这里丢失。不,我无法编译
-
那(仍然)不能是您的真实代码,因为缺少
return true。 – 我在 Xcode 10.1 中创建了一个新的 iOS 项目,并在 didFinishLaunchingWithOptions 方法中添加了NSSetUncaughtExceptionHandler { (exception) in print(exception) },它编译没有问题。 -
@MartinR 我正在使用 xcode 10.1,但我忘记在此处编写刚刚编辑的 return true。但我仍然得到我说的错误。我刚刚找到这个链接“stackoverflow.com/questions/25441302/…”但我不明白答案。
-
@Niloufar:您必须在读取/解码/任何内容的地方直接处理... API 响应,使用常用工具(检查 nil、可选绑定、可选强制转换、guard . ..)。 – 全局异常处理程序不是用于该目的的正确工具。
标签: ios swift exception-handling nsexception