我决定使用NSSecureCoding
over NSCoding
,但我无法让它工作。
我希望以下代码会失败,因为我正在编码一个NSString
但试图解码一个NSNumber
. 但是,该对象被初始化而不会引发异常。
+ (BOOL)supportsSecureCoding
{
return YES;
}
- (instancetype)initWithCoder:(NSCoder *)coder
{
// prints '1' as expected
NSLog(@"%d", coder.requiresSecureCoding);
// unexpectedly prints 'foo' (expecting crash)
NSLog(@"%@", [coder decodeObjectOfClass:NSNumber.class forKey:@"bar"]);
return [super init];
}
- (void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeObject:@"foo" forKey:@"bar"];
}
这是我用来测试上面代码片段的代码:
MyClass *object = [[MyClass alloc] init];
NSMutableData *const data = [[NSMutableData alloc] init];
NSKeyedArchiver *const archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
archiver.requiresSecureCoding = YES;
[archiver encodeObject:object forKey:@"root"];
[archiver finishEncoding];
NSKeyedUnarchiver *const unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
unarchiver.requiresSecureCoding = YES;
[unarchiver decodeObjectOfClass:MyClass.class forKey:@"root"];
[unarchiver finishDecoding];
我是否遗漏了一些完全明显的东西,或者为什么在解码过程中没有抛出异常?