1

是否可以使用 NSSecureCoding 将 UIView 写入磁盘。下面的代码会导致错误。

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:object requiringSecureCoding:YES error:&error];

错误:无法写入数据,因为它的格式不正确。

我们还尝试了以下方法:

NSMutableData *data = [NSMutableData data];
NSKeyedArchiver  *archiver = [[NSKeyedArchiver alloc] initRequiringSecureCoding:YES];
[archiver encodeObject:view forKey:@"view"];
[archiver finishEncoding];

错误:此解码器将仅解码采用 NSSecureCoding 的类。'UIView' 类不采用它。

4

1 回答 1

1

NSSecureCoding,除了 NSCoding 的要求,只需要类实现一个类函数 +(BOOL)supportsSecureCoding。UIView 已经支持 NSCoding 并且它似乎可能是一个疏忽,它还没有符合 NSSecureCoding;Xcode 调试器会发出有关非 NSSecureCoding 序列化调用在遥远的将来消失的警告。

您可以使用类别将类函数添加到 UIView:

@interface UIView(SecureCoding)<NSSecureCoding>
@end

@implementation UIView(SecureCoding)
+ (BOOL)supportsSecureCoding {
    return TRUE;
}
@end

正如评论中所指出的,这并不意味着您可以使用 NSKeyedUnarchiver 进行反序列化,因为 UIView 似乎不打算以这种方式进行序列化。我猜他们支持序列化的主要原因是 xibs/nibs/storyboards。这是一个 UIView 序列化的示例,它确实有效,但使用私有 API,因此仅用于说明目的:

添加声明以访问未发布的 API:

/* Warning: Unpublished APIs!*/
@interface UINibEncoder : NSCoder
- initForWritingWithMutableData:(NSMutableData*)data;
- (void)finishEncoding;
@end

@interface UINibDecoder : NSCoder
- initForReadingWithData:(NSData *)data error:(NSError **)err;
@end

序列化/反序列化:

/* This does NOT work */
NSKeyedArchiver  *archiver = [[NSKeyedArchiver alloc] initRequiringSecureCoding:NO];
[archiver encodeObject:object forKey:@"view"];
[archiver finishEncoding];
data = [archiver encodedData];


NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingFromData:data error:&error];
/* error: 'UIBackgroundColor' was of unexpected class 'UIColor' */
data = [unarchiver decodeObjectForKey:@"view"];


/* This DOES work, but don't use it in an app you plan to publish */
NSMutableData *mData = [NSMutableData new];
UINibEncoder *encoder = [[UINibEncoder alloc] initForWritingWithMutableData:mData];

[encoder encodeObject:object forKey:@"view"];
[encoder finishEncoding];

UINibDecoder *decoder = [[UINibDecoder alloc] initForReadingWithData:mData error:&error];
NSObject *myView = [decoder decodeObjectForKey:@"view"];
于 2021-06-14T23:04:47.867 回答