ios – NSKeyedUnarchiver错误处理 – 防止在Swift中崩溃

前端之家收集整理的这篇文章主要介绍了ios – NSKeyedUnarchiver错误处理 – 防止在Swift中崩溃前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
由于 Swift目前没有try-catch,我应该如何防止这行代码中的错误数据崩溃?
var myObject = NSKeyedUnarchiver.unarchiveObjectWithData(data) as MyClass

UPDATE

我在操场上创造了一个非常简单的案例来进行演示.假设我们不知道数据是什么,如何在第二行捕获SIGABRT?是否没有办法检查以确保在调用unarchiveObjectWithData之前可以取消归档NSData对象?

var data = "foo bar".dataUsingEncoding(NSUTF8StringEncoding,allowLossyConversion: true)!
if let unarc = NSKeyedUnarchiver.unarchiveObjectWithData(data) { // Execution was interrupted: signal SIGABRT
}

解决方法

我认为现在最好的赌注是,直到Apple更新NSKeyedUnarchiver的实现才能使用异常或者向Swift添加异常支持,您将不得不使用Objective-C包装器来尝试捕获.

您可以在这里看到一个包装器的例子:
https://medium.com/swift-programming/adding-try-catch-to-swift-71ab27bcb5b8

基本上,您可以引入一个单一的Objective-C函数或类,这将允许您使用Swift的try-catch块.我喜欢将上述示例作为初始化器来实现,使其在Swift中更清晰:

// In Objective-C
// ----------------------

@interface try: NSObject

- (id)initWithTry:(void(^)())try catch:(void(^)(NSException *exception))catch finally:(void(^)())finally;

@end

@implementation try

- (id)initWithTry:(void(^)())try catch:(void(^)(NSException *exception))catch finally:(void(^)())finally
{
    self = [super init];
    if (self) {
        @try {
            try ? try() : nil;
        }
        @catch (NSException *exception) {
            catch ? catch(exception) : nil;
        }
        @finally {
            finally ? finally() : nil;
        }
    }
    return self;
}

@end

// From Swift (make sure you import the objc header in your bridging header
// ----------------------

var data = "foo bar".dataUsingEncoding(NSUTF8StringEncoding,allowLossyConversion: true)!
try(
    try: { () -> Void in
        if let unarc: AnyObject = NSKeyedUnarchiver.unarchiveObjectWithData(data) { // Execution was interrupted: signal SIGABRT
            println(unarc)
        }
    },catch: { exception in
        println("Failed to parse data: \(exception)")
    },finally: nil
)

猜你在找的iOS相关文章