Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

ios - How should I use NSSetUncaughtExceptionHandler in Swift

At Objective-C, I call the NSSetUncaughtExceptionHandler(&exceptionHandler) method to log exceptions. How does it called in Swift?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As of Swift 2 (Xcode 7), you can pass Swift functions/closures to parameters taking a C function pointer. From the Xcode 7 release notes:

Native support for C function pointers: C functions that take function pointer arguments can be called using closures or global functions, with the restriction that the closure must not capture any of its local context.

So this compiles and works:

func exceptionHandler(exception : NSException) {
    print(exception)
    print(exception.callStackSymbols)
}

NSSetUncaughtExceptionHandler(exceptionHandler)

Or with an "inline" closure:

NSSetUncaughtExceptionHandler { exception in
    print(exception)
    print(exception.callStackSymbols)
}

This does exactly the same as the corresponding Objective-C code: it catches otherwise uncaught NSExceptions. So this will be caught:

let array = NSArray()
let elem = array.objectAtIndex(99)

NOTE:- It does not catch any Swift 2 errors (from throw) or Swift runtime errors, so this is not caught:

let arr = [1, 2, 3]
let elem = arr[4]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...