我应该如何在 Swift 中使用 NSSetUncaughtExceptionHandler [英] How should I use NSSetUncaughtExceptionHandler in Swift
问题描述
在 Objective-C 中,我调用 NSSetUncaughtExceptionHandler(&exceptionHandler)
方法来记录异常.它在 Swift 中是如何调用的?
At Objective-C, I call the NSSetUncaughtExceptionHandler(&exceptionHandler)
method to log exceptions. How does it called in Swift?
推荐答案
更新
使用 Swift 2,您可以将 Swift 函数和闭包作为 C 函数指针传递.参见下面 Martin R 的回答.
你不能,从 Xcode 6 beta 6 开始.
You can't, as of Xcode 6 beta 6.
Swift 确实支持传递函数指针,但它们被视为不透明指针.您既不能定义指向 Swift 函数的 C 函数指针,也不能在 Swift 中调用 C 函数指针.
Swift does support passing around function pointers, but they're treated pretty much like opaque pointers. You can't neither define a C function pointer to a Swift function nor can you call a C function pointer in Swift.
这意味着您从 Swift 中调用了 NSSetUncaughtExceptionHandler()
,但是处理程序必须在 Objective-C 中实现.你需要一个这样的头文件:
That means you call NSSetUncaughtExceptionHandler()
from Swift, but the handler must be implemented in Objective-C. You need a header file like this:
volatile void exceptionHandler(NSException *exception);
extern NSUncaughtExceptionHandler *exceptionHandlerPtr;
在实现中,你需要这样的东西:
and in the implementation, you need something like this:
volatile void exceptionHandler(NSException *exception) {
// Do stuff
}
NSUncaughtExceptionHandler *exceptionHandlerPtr = &exceptionHandler;
在 Swift 桥接头中导入头文件后,您可以照常设置异常处理程序:
After you imported the header file in the Swift bridging header, you can set up the exception handler as usual:
NSSetUncaughtExceptionHandler(exceptionHandlerPtr)
这篇关于我应该如何在 Swift 中使用 NSSetUncaughtExceptionHandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!