iOS13歸檔功能削弱了流部??纹坐?枝冀?,感覺object-c
已經(jīng)不是Apple的親兒子了耘子,swift
才是Apple的親兒子宾茂。
@interface Model : NSObject <NSCoding>
@property (nonatomic, strong) NSString *title;
@end
@implementation Model
- (instancetype)init
{
self = [super init];
if (self) {
self.title = @"sssss";
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super init];
if (self) {
self.title = [coder decodeObjectForKey:@"title"];
}
return self;
}
- (void)encodeWithCoder:(nonnull NSCoder *)coder {
[coder encodeObject:self.title forKey:@"title"];
}
@end
1. NSKeyedArchiver
歸檔
archiveRootObject:toFile:
在iOS13中已棄用,替換為archivedDataWithRootObject:requiringSecureCoding:error:
拴还,可以歸檔任何類型。
Model *model = [[Model alloc] init];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:model requiringSecureCoding:false error:nil];
2. NSKeyedUnarchiver
解檔
unarchiveObjectWithFile:
同樣在iOS13中被棄用欧聘,替換為unarchivedObjectOfClass:fromData:error:
Model *model0 = [NSKeyedUnarchiver unarchivedObjectOfClass:[Model class] fromData:data error:nil];
報錯:
Error Domain=NSCocoaErrorDomain Code=4864 "This decoder will only decode classes that adopt NSSecureCoding. Class 'Model' does not adopt it." UserInfo={NSDebugDescription=This decoder will only decode classes that adopt NSSecureCoding. Class 'Model' does not adopt it.}
分析錯誤注意到另一個協(xié)議NSSecureCoding
@interface Model : NSObject <NSCoding, NSSecureCoding>
@property (nonatomic, strong) NSString *title;
@end
+ (BOOL)supportsSecureCoding {
return YES;
}
此處必須返回
YES
片林,如果返回NO
同樣會報錯。
Error Domain=NSCocoaErrorDomain Code=4864 "Class 'Model' disallows secure coding. It must return YES from supportsSecureCoding." UserInfo={NSDebugDescription=Class 'Model' disallows secure coding. It must return YES from supportsSecureCoding.}
解檔的大坑
如果其中存在NSArray
等集合怀骤,那么解檔同樣會失敗费封,不知原因。
@interface Model : NSObject <NSCoding, NSSecureCoding>
@property (nonatomic, strong) NSArray *title;
@end
報錯:
Error Domain=NSCocoaErrorDomain Code=4864 "value for key 'title' was of unexpected class 'NSArray'. Allowed classes are '{( Model )}'." UserInfo={NSDebugDescription=value for key 'title' was of unexpected class 'NSArray'. Allowed classes are '{( Model )}'.}
@interface Model : NSObject <NSCoding, NSSecureCoding>
@property (nonatomic, strong) NSDictionary *title;
@end
報錯:
Error Domain=NSCocoaErrorDomain Code=4864 "value for key 'title' was of unexpected class 'NSDictionary'. Allowed classes are '{( Model )}'." UserInfo={NSDebugDescription=value for key 'title' was of unexpected class 'NSDictionary'. Allowed classes are '{( Model )}'.}
解決方案
- 建議轉(zhuǎn)化為
JOSN
字符串蒋伦,再進行歸檔解檔 - 使用其他本地化方案