NSCoding、NSSecureCoding、NSCopying

NSCoding

存与取

NSCoding是把数据存储在iOS和Mac OS上的一种极其简单和方便的方式,它把模型对象直接转变成一个文件,然后再把这个文件重新加载到内存里,并不需要任何文件解析和序列化的逻辑。如果要把对象保存到一个数据文件中(假设这个对象实现了NSCoding协议),你可以这样做咯:

//存到本地
Book *book = [[Book alloc] init];
[NSKeyedArchiver archiveRootObject:book toFile:filePath];

//从本地取出
Book *theBook = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

如何写遵循NSCoding协议的类

实现两个方法- (void)encodeWithCoder:(NSCoder *)aCoder- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder,举个刚刚Book类的栗子:

- (void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:self.title forKey:@"title"];
    [aCoder encodeObject:self.author forKey:@"author"];
    [aCoder encodeBool:self.isPublished forKey:@"isPublished"];    
}

- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super init];
    if (self) {
        self.title = [aDecoder decodeObjectForKey:@"title"];
        self.author = [aDecoder decodeObjectForKey:@"author"];
        self.isPublished = [aDecoder decodeBoolForKey:@"isPublished"];
    }
    return self;
}

NSSecureCoding

NSSecureCoding是NSCoding的变种,因为NSCoding毕竟不太安全,大部分支持NSCoding的系统对象都已经升级到支持NSSecureCoding了,如AFNetworking的AFURLSessionManager,下面老衲举个栗子:

存与取

NSData *data = [NSData dataWithContentsOfFile:filePath];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
[unarchiver setRequiresSecureCoding:YES];
 
//解码
Foo *someFoo = [unarchiver decodeObjectForKey:NSKeyedArchiveRootObjectKey];

如何遵循协议

在原来encodeWithCoderinitWithCoder的基础上增加supportsSecureCoding,如下

- (void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:self.title forKey:@"title"];
    [aCoder encodeObject:self.author forKey:@"author"];
    [aCoder encodeBool:self.isPublished forKey:@"isPublished"];
}

- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super init];
    if (self) {
        self.title = [aDecoder decodeObjectForKey:@"title"];
        self.author = [aDecoder decodeObjectForKey:@"author"];
        self.isPublished = [aDecoder decodeBoolForKey:@"isPublished"];
    }
    return self;
}

+ (BOOL)supportsSecureCoding{
    return YES;
}

NSCopying

NSCopying是一个与对象拷贝有关的协议。如果想让一个类的对象支持拷贝,就需要让该类实现NSCopying协议。NSCopying协议中的声明的方法只有一个- (id)copyWithZone:(NSZone *)zone。当我们的类实现了NSCopying协议,通过类的对象调用copy方法时,copy方法就会去调用我们实现的- (id)copyWithZone:(NSZone *)zone方法,实现拷贝功能。比如AFN里对session的configuration进行了拷贝:

- (instancetype)copyWithZone:(NSZone *)zone {
    return [[[self class] allocWithZone:zone] initWithSessionConfiguration:self.session.configuration];
}

你可能感兴趣的:(NSCoding、NSSecureCoding、NSCopying)