TestModel.h 文件 列举了4个类型 NSString、BOOL、NSNumber、Object
#import <Foundation/Foundation.h>
#import "TestSubModel.h"
@interface TestModel : NSObject <NSSecureCoding>
@property (nonatomic ,strong) NSString * name;
@property (nonatomic ,assign) NSInteger age;
@property (nonatomic ,assign) BOOL isSelect;
@property (nonatomic ,strong) TestSubModel *subModel;
@end
TestModel.m 文件
#import "TestModel.h"
@implementation TestModel
- (nullable instancetype)initWithCoder:(nonnull NSCoder *)coder
{
if (self == [super init]) {
self.name = [coder decodeObjectOfClass:[NSString class] forKey:NSStringFromSelector(@selector(name))];
self.age = [[coder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(age))] unsignedIntegerValue];
self.isSelect = [coder decodeBoolForKey:NSStringFromSelector(@selector(isSelect))];
self.subModel = [coder decodeObjectOfClass:[TestSubModel class] forKey:NSStringFromSelector(@selector(subModel))];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeObject:self.name forKey:NSStringFromSelector(@selector(name))];
[coder encodeObject:[NSNumber numberWithUnsignedInteger:self.age] forKey:NSStringFromSelector(@selector(age))];
[coder encodeBool:self.isSelect forKey:NSStringFromSelector(@selector(isSelect))];
[coder encodeObject:self.subModel forKey:NSStringFromSelector(@selector(subModel))];
}
// 这个需要返回YES
+ (BOOL)supportsSecureCoding
{
return YES;
}
@end
TestSubModel.h 文件
#import <Foundation/Foundation.h>
@interface TestSubModel : NSObject <NSSecureCoding>
@property (nonatomic ,strong) NSString * xiao;
@property (nonatomic ,assign) NSInteger shuzi;
@end
发现上面的TestModel 如果写MJExtension 的方法最后解档取值是空,但是子模型可以写 MJExtension的归解档方法
TestSubModel.m 文件
#import <MJExtension.h>
@implementation TestSubModel
- (nullable instancetype)initWithCoder:(nonnull NSCoder *)coder
{
if (self == [super init]) {
[self mj_decode:coder];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder
{
[self mj_encode:coder];
}
// 这个需要返回YES
+ (BOOL)supportsSecureCoding
{
return YES;
}
@end
归档
NSError * error;
NSData * data = [NSKeyedArchiver archivedDataWithRootObject:model requiringSecureCoding:YES error:&error];
解档
TestModel * result = (TestModel*)[NSKeyedUnarchiver unarchivedObjectOfClass:[TestModel class] fromData:data error:&error];
NSLog(@"---result-------%li-%@ %i- %@ -%li--------",result.age,result.name,result.isSelect,result.subModel.xiao,result.subModel.shuzi);