NSSecureCoding协议demo

1.自定义一个User类,实现NSSecureCoding协议

@interface User : NSObject 

@property(nonatomic, strong)NSString *user;
@property(nonatomic, strong)NSArray *books;
@property(nonatomic, assign)int age;

@end
@implementation User

+(instancetype)model{
    User *user = [[User alloc] init];
    user.user = @"user";
    user.books = @[@"精通Objective-C设计模式",@"图解HTTP",@"解忧杂货店"];
    user.age = 24;
    return user;
}

+ (BOOL)supportsSecureCoding{
    return YES;
}

- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder;{
    self = [super init];
    if (self) {
        self.user = [aDecoder decodeObjectOfClass:[NSString class] forKey:@"user"];
        self.books = [aDecoder decodeObjectOfClass:[NSArray class] forKey:@"books"];
        self.age = [aDecoder decodeIntForKey:@"age"];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:_user forKey:@"user"];
    [aCoder encodeObject:_books forKey:@"books"];
    [aCoder encodeInt:_age forKey:@"age"];
}

2.Archive

User *user = [User model];
NSMutableData *data = [NSMutableData data];
NSKeyedArchiver *archive = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
archive.requiresSecureCoding = YES;
[archive encodeObject:user forKey:NSKeyedArchiveRootObjectKey];
[archive finishEncoding]; //encode完之后,必须调用此方法
[data writeToFile:[self filePath] atomically:YES];

3.Unarchive

NSData *data = [[NSData alloc] initWithContentsOfFile:[self filePath]];
NSKeyedUnarchiver *unarchive = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
unarchive.requiresSecureCoding = YES;
User *user = [unarchive decodeObjectOfClass:[User class] forKey:NSKeyedArchiveRootObjectKey];
[unarchive finishDecoding]; //可调用或者可不调用?

你可能感兴趣的:(NSSecureCoding协议demo)