![](/img/trans.png)
[英]iOS - unarchive NSSecureCoding Object that has a property of type Date
[英]NSSecureCoding: Writing UIView to disk
是否可以使用 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 的類。 Class 'UIView' 不采用它。
NSSecureCoding,除了 NSCoding 要求,只需要 class 來實現 class function +(BOOL)supportsSecureCoding。 UIView 已經支持 NSCoding 並且它似乎可能是一個疏忽,它還沒有符合 NSSecureCoding; Xcode 調試器發出關於非 NSSecureCoding 序列化調用在遙遠的將來消失的警告。
您可以使用以下類別將 class function 添加到 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"];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.