【问题标题】:How to use NSSetUncaughtExceptionHandler to show exception message on UIView in Swift如何使用 NSSetUncaughtExceptionHandler 在 Swift 中的 UIView 上显示异常消息
【发布时间】:2015-10-05 15:47:45
【问题描述】:

我使用 Martin R 的答案在 Swift 中打印 NSSetUncaughtExceptionHandler。

How should I use NSSetUncaughtExceptionHandler in Swift

  func exceptionHandler(exception : NSException) {

    let alert = UIAlertController(title: "Exception", message: "\(exception)", preferredStyle: .Alert)

    self.presentViewController(alert, animated: true, completion: nil)

    print(exception)
    print(exception.callStackSymbols)
}

但是如何在 UIView 中显示消息。喜欢这个

因为我收到一条编译器错误消息,说“C 函数指针只能由对 'func' 的引用或文字闭包形成。”

Handling unhandled exceptions and signals 由 Matt Gallagher 在 Cocoa with Love 撰写。

【问题讨论】:

  • 你试过 exception.name 或 exception.reason 吗?
  • @Horst,我想在屏幕上显示消息,用户可以捕获并发回。
  • 你没有显示你的整个代码
  • @newacct 我是 Swift 新手,大约只有 1 年。我正在尝试将 Matt 编写的代码从 ObjC 转换为 Swift。它可以编译,但不能运行。 'int retVal = UIApplicationMain(argc, argv, nil, nil);' 行中 main.m 中的错误消息 'Thread 1: singal SIGABRT'
  • @charles.cc.hsu:我很困惑。你不是说你有编译错误吗?

标签: ios swift exception uiview


【解决方案1】:

NSSetUncaughtExceptionHandler 接受一个 C 函数指针,而 C 函数体在编译时是固定的。 C 函数指针作为 @convention(c) 函数类型桥接到 Swift 2 中,并且与 C 中一样,您只能传递其主体可以在编译时修复的函数;即顶级 Swift 函数,或不捕获任何变量的匿名函数。

您的匿名函数从封闭范围捕获self,因此它不能用作C 函数。您应该尝试仅使用全局变量或类来访问控制器或以其他方式执行您需要执行的任何操作。

【讨论】:

  • 谢谢!我将按照您的建议找出解决方案。在此之前,我可能只是保留原来的 C 函数并使用 bridge 来处理 Swift。
  • @charles.cc.hsu:你会如何把它写成 C 函数?如果你能回答他们,你可以在不捕获任何变量的情况下用 Swift 编写它。
  • 我仍在努力将C code 转换为 Swift,因为我也不熟悉 ObjC。 UncaughtExceptionHandler.m 对我来说太低级了。我不知道'volatile'的含义以及如何将其转换为 Swift(SO 中的某处说使用 memset_s)。其次,不推荐使用 UIAlertView 的代码,我也不知道如何将其转换为 UIAlertController,因为 UncaughtExceptionHandler 只是 NSObject 的子类。
  • 这里有一个解决方案[来自任何 NSObject 子类的 UIAlertController] (stackoverflow.com/questions/31472321/…),我会试一试。
  • 如何释放内存?
【解决方案2】:

使用 NSSetUncaughtExceptionHandler

NSSetUncaughtExceptionHandler { exception in
            print("EXception Details Are \n\nExceptionName--> \(exception.name) \nReason -->\(exception.reason!)\n\(exception.description)")
            print(exception.callStackSymbols)
        }

【讨论】:

  • 多解释一下
  • 我也在尝试这个。我收到同样的错误。你是怎么解决这个问题的?现在我发现同样的错误。我需要邮寄那个错误。但我不能
猜你喜欢
  • 2011-09-01
  • 2020-05-30
  • 2019-09-18
  • 2021-12-24
  • 2019-06-13
  • 1970-01-01
  • 1970-01-01
  • 2014-10-15
  • 1970-01-01
相关资源
最近更新 更多