iOS经验总结数据储存

ios 13 归档解档

2019-10-31  本文已影响0人  迷路的小小

iOS13归档功能削弱了????,感觉object-c已经不是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.}

分析错误注意到另一个协议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 )}'.}

解决方案

  1. 建议转化为JOSN字符串,再进行归档解档
  2. 使用其他本地化方案
上一篇 下一篇

猜你喜欢

热点阅读