如何在Swift中使用NSSetUncaughtExceptionHandler [英] How should I use NSSetUncaughtExceptionHandler in Swift

查看:288
本文介绍了如何在Swift中使用NSSetUncaughtExceptionHandler的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中,我调用 NSSetUncaughtExceptionHandler(& exceptionHandler)方法来记录异常。在Swift中如何调用?

解决方案

更新



2,可以将Swift函数和闭包作为C函数指针。 请参阅Martin R的以下答案



原始答案



你不能,从Xcode 6 beta 6。



Swift确实支持传递函数指针,几乎看不透明的指针。你不能既不定义一个指向Swift函数的C函数指针,也不能在Swift中调用C函数指针。



这意味着你调用来自Swift的NSSetUncaughtExceptionHandler(),但是处理程序必须在Objective-C中实现。您需要这样的头文件:

  volatile void exceptionHandler(NSException * exception); 
extern NSUncaughtExceptionHandler * exceptionHandlerPtr;

在实现中,您需要这样:

  volatile void exceptionHandler(NSException * exception){
// Do stuff
}
NSUncaughtExceptionHandler * exceptionHandlerPtr =& exceptionHandler;

在Swift桥接头中导入头文件后,可以像往常一样设置异常处理程序:

  NSSetUncaughtExceptionHandler(exceptionHandlerPtr)
pre>

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

解决方案

Update

With Swift 2, you can pass Swift functions and closures as C function pointer. See Martin R's answer below.

Original answer

You can't, as of Xcode 6 beta 6.

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.

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;

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆