How to use NSSetUncaughtExceptionHandler to show e

2019-02-28 18:50发布

问题:

I use Martin R's answer to print the NSSetUncaughtExceptionHandler in Swift.

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)
}

But how can I display the message in a UIView. Like this one

Because I got a compiler error message said that "A C function pointer can only be formed from a reference to a 'func' or a literal closure."

Handling unhandled exceptions and signals written by Matt Gallagher at Cocoa with Love.

回答1:

NSSetUncaughtExceptionHandler takes a C function pointer, and C function bodies are fixed at compile-time. C function pointers get bridged into Swift 2 as @convention(c) function types, and, like in C, you can only pass a function whose body can be fixed at compile-time; i.e. top-level Swift functions, or anonymous function which don't capture any variables.

Your anonymous function captures self from the enclosing scope, so it cannot be used as a C function. You should try to access the controller or do whatever you need to do in some other way using only global variables or classes.



回答2:

with the use of NSSetUncaughtExceptionHandler

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