如何在Swift中捕获NSKeyedUnarchiver“ NSInvalidUnarchiveOperationException”?

时间:2018-08-11 16:49:46

标签: swift codable nskeyedunarchiver

我在Swift中将CodableNSKeyedArchiverNSKeyedUnarchiver结合使用来进行对象解密/解码。

当编码的对象与期望的格式匹配时,效果很好。 但是,如果数据无效或格式不匹配,我将在使用XCTest的单元测试中得到以下断言:

  

失败:捕获到“ NSInvalidUnarchiveOperationException”,“由于格式不正确,无法读取数据。”

我使用的是NSKeyedUnarchiver.decodeTopLevelDecodable方法,解码失败时使用的是which is supposed to throw an exception

  

如果归档文件不是有效的属性列表,则此方法将引发DecodingError.dataCorrupted(_:)错误。如果存档中的值无法解码,则此方法将引发相应的错误。

由于try?do/catchXCTAssertThrowsError似乎都无法正常工作,我无法捕获此异常。

测试失败时的完整错误消息:

failed: caught "NSInvalidUnarchiveOperationException", "The data couldn’t be read because it isn’t in the correct format."
(
    0   CoreFoundation                      0x00007fff315f12db __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x00007fff587a1c76 objc_exception_throw + 48
    2   Foundation                          0x00007fff3376b077 -[NSCoder(Exceptions) __failWithExceptionName:errorCode:format:] + 0
    3   Foundation                          0x00007fff3376b371 -[NSCoder(Exceptions) __failWithExternalError:] + 161
    4   libswiftFoundation.dylib            0x0000000109872453 _T0So17NSKeyedUnarchiverC10FoundationE23decodeTopLevelDecodablexSgxm_SS6forKeytKs0G0RzlF + 403
    5   MBOUtilityKit                       0x0000000104cba964 _T013MBOUtilityKit17KeyedLocalStorageV3getxSS3key_tKs9DecodableRzs9EncodableRzlF + 772
    6   MBOUtilityKitTests macOS            0x0000000104c5144c _T024MBOUtilityKitTests_macOS017KeyedLocalStorageC0C17testDecodeFailureyyKF + 556
    7   MBOUtilityKitTests macOS            0x0000000104c51835 _T024MBOUtilityKitTests_macOS017KeyedLocalStorageC0C17testDecodeFailureyyKFTo + 69
    8   CoreFoundation                      0x00007fff31568bec __invoking___ + 140
    9   CoreFoundation                      0x00007fff31568ac0 -[NSInvocation invoke] + 320
    10  XCTest                              0x000000010036c90d __24-[XCTestCase invokeTest]_block_invoke_2.187 + 65
    11  XCTest                              0x00000001003d6207 -[XCTMemoryChecker _assertInvalidObjectsDeallocatedAfterScope:] + 51
    12  XCTest                              0x00000001003755ef -[XCTestCase assertInvalidObjectsDeallocatedAfterScope:] + 116
    13  XCTest                              0x000000010036c89c __24-[XCTestCase invokeTest]_block_invoke.181 + 210
    14  XCTest                              0x00000001003c8772 +[XCTestCase(Failures) performFailableBlock:shouldInterruptTest:] + 36
    15  XCTest                              0x00000001003c86bc -[XCTestCase(Failures) _performTurningExceptionsIntoFailuresInterruptAfterHandling:block:] + 54
    16  XCTest                              0x000000010036c4db __24-[XCTestCase invokeTest]_block_invoke + 854
    17  XCTest                              0x00000001003cd659 -[XCUITestContext performInScope:] + 237
    18  XCTest                              0x000000010036c170 -[XCTestCase invokeTest] + 175
    19  XCTest                              0x000000010036dea6 __26-[XCTestCase performTest:]_block_invoke_2 + 42
    20  XCTest                              0x00000001003c8772 +[XCTestCase(Failures) performFailableBlock:shouldInterruptTest:] + 36
    21  XCTest                              0x00000001003c86bc -[XCTestCase(Failures) _performTurningExceptionsIntoFailuresInterruptAfterHandling:block:] + 54
    22  XCTest                              0x000000010036dd53 __26-[XCTestCase performTest:]_block_invoke.326 + 90
    23  XCTest                              0x00000001003d24a1 +[XCTContext runInContextForTestCase:block:] + 225
    24  XCTest                              0x000000010036d454 -[XCTestCase performTest:] + 673
    25  XCTest                              0x00000001003b0555 -[XCTest runTest] + 57
    26  XCTest                              0x0000000100368b30 __27-[XCTestSuite performTest:]_block_invoke + 365
    27  XCTest                              0x000000010036830c -[XCTestSuite _performProtectedSectionForTest:testSection:] + 55
    28  XCTest                              0x00000001003685cd -[XCTestSuite performTest:] + 296
    29  XCTest                              0x00000001003b0555 -[XCTest runTest] + 57
    30  XCTest                              0x0000000100368b30 __27-[XCTestSuite performTest:]_block_invoke + 365
    31  XCTest                              0x000000010036830c -[XCTestSuite _performProtectedSectionForTest:testSection:] + 55
    32  XCTest                              0x00000001003685cd -[XCTestSuite performTest:] + 296
    33  XCTest                              0x00000001003b0555 -[XCTest runTest] + 57
    34  XCTest                              0x0000000100368b30 __27-[XCTestSuite performTest:]_block_invoke + 365
    35  XCTest                              0x000000010036830c -[XCTestSuite _performProtectedSectionForTest:testSection:] + 55
    36  XCTest                              0x00000001003685cd -[XCTestSuite performTest:] + 296
    37  XCTest                              0x00000001003b0555 -[XCTest runTest] + 57
    38  XCTest                              0x00000001003e6308 __44-[XCTTestRunSession runTestsAndReturnError:]_block_invoke + 40
    39  XCTest                              0x000000010038aaa4 -[XCTestObservationCenter _observeTestExecutionForBlock:] + 600
    40  XCTest                              0x00000001003e610e -[XCTTestRunSession runTestsAndReturnError:] + 369
    41  XCTest                              0x000000010034f865 -[XCTestDriver runTestsAndReturnError:] + 440
    42  XCTest                              0x00000001003d10f3 _XCTestMain + 1228
    43  xctest                              0x0000000100002155 main + 557
    44  libdyld.dylib                       0x00007fff593bb015 start + 1
    45  ???                                 0x0000000000000005 0x0 + 5
)

3 个答案:

答案 0 :(得分:2)

未正确设置该类的Objective-C桥以在Swift中引发错误,因此您将必须创建引发或捕获错误的Objective-C包装器。

这是我超级简单的“ SafeUnarchiver”,您可以从中激发自己的灵感:

SafeUnarchiver.h:

#import <Foundation/Foundation.h>

@interface SafeUnarchiver : NSObject
+(NSObject* _Nullable)unarchive:(NSData* _Nonnull)data;
@end

SafeUnarchiver.m:

#import "SafeUnarchiver.h"

@implementation SafeUnarchiver
+(NSObject *)unarchive:(NSData *)data {
    @try {
        id object = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        return object;
    } @catch (NSException *exception) {
        NSLog(@"ERROR attempting to unarchive object: %@", exception);
    }
    return nil;
}
@end

别忘了向Apple提交Radar票证,这样他们最终可以解决未正确捕获的异常。

根据您要从Swift访问的其他Objective-C代码,您必须将标头添加到-Bridging-Header.h

答案 1 :(得分:1)

从iOS 9开始,您可以使用:unarchiveTopLevelObjectWithData(_:),它会引发异常。

示例:

try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data)

https://developer.apple.com/documentation/foundation/nskeyedunarchiver/2919664-unarchivetoplevelobjectwithdata

答案 2 :(得分:0)

您需要像这样设置取消存档失败的策略:

let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
unarchiver.decodingFailurePolicy = .setErrorAndReturn

这将使NSKeyedUnarchiver返回NSError,它将被正确转换为可以捕获的迅速异常。