最近碰上iOS解档的时候报错了,错误是
value for key 'NS.objects' was of unexpected class解决方案
。
iOS 11之前直接使用如下方法就可以进行归档,而且还可以直接取出转成自己需要的model,可是iOS 11不能这样弄了
NSArray * < testModel *> testArr = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
iOS 11 之后官方文档又给出了几个新方法,当然我这里就用了一个所以这里就拿下边的方法做说明。
使用方法
JCTestModel,JCTestModel.h如下所示
需要注意一定要遵守
NSSecureCoding
协议
@interface JCTestModel : NSObject<NSSecureCoding> @property (nonatomic, copy) NSString *late; @property (nonatomic, copy) NSString *rore; @property (nonatomic, copy) NSString *ation; @property (nonatomic, copy) NSString *mode; - (instancetype)initWithLate:(NSString *)late rore:(NSString *)rore ation:(NSString *)ation mode:(NSString *)mode; @end
JCTestModel.m如下所示
需要注意
supportsSecureCoding
这个方法一定要设置为YES
#import "JCTestModel.h" @implementation JCTestModel - (instancetype)initWithLate:(NSString *)late rore:(NSString *)rore ation:(NSString *)ation mode:(NSString *)mode{ self = [super init]; if (self) { _late = late; _rore = rore; _mode = mode; _ation = ation; } return self; } - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:self.late forKey:@"late"]; [aCoder encodeObject:self.rore forKey:@"rore"]; [aCoder encodeObject:self.mode forKey:@"mode"]; [aCoder encodeObject:self.ation forKey:@"ation"]; } - (instancetype)initWithCoder:(NSCoder *)aDecoder { self = [super init]; if (self) { _late = [aDecoder decodeObjectForKey:@"late"]; _rore = [aDecoder decodeObjectForKey:@"rore"]; _mode = [aDecoder decodeObjectForKey:@"mode"]; _ation = [aDecoder decodeObjectForKey:@"ation"]; } return self; } + (BOOL)supportsSecureCoding{ return YES; } @end
注意事项
1.保存数据的时候需要注意下边方法中的
requiringSecureCoding
一定要设置成YES
否则劳动半天不起作用
- (void)saveData:(NSMutableArray<JCTestModel *> *)data { NSString *filePath = @"这里写你自己本地缓存的地址"; NSData *data = [NSKeyedArchiver archivedDataWithRootObject:data requiringSecureCoding:YES error:nil]; [data writeToFile:filePath atomically:YES]; }
2.读取数据的时候也需要注意一定要把你用到的数据类型都传进
NSSet
中。不然xcode也会报错的。
NSSet *allSet = [NSSet setWithObjects: [NSArray class], [JCTestModel class], [NSString class], nil]; NSArray *unarchivedObjects = [NSKeyedUnarchiver unarchivedObjectOfClasses:allSet fromData:data error:&error];