NSSecureCoding协议demo

2017-01-20  本文已影响98人  ONE2

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

@interface User : NSObject <NSSecureCoding>

@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]; //可调用或者可不调用?
上一篇下一篇

猜你喜欢

热点阅读