美文网首页
iOS NSCoding 与 NSSecureCoding

iOS NSCoding 与 NSSecureCoding

作者: iOS_肖晨 | 来源:发表于2018-03-01 14:09 被阅读65次

    NSCoding

    • 简介
      NSCoding是把数据存储在iOS和Mac OS上的一种极其简单和方便的方式,它把模型对象直接转变成一个文件,然后再把这个文件重新加载到内存里,并不需要任何文件解析和序列化的逻辑。
    • 使用
      对象需要实现了NSCoding协议
    // 存储
    Teacher *t = [[Teacher alloc] init];
    t.name = [NSMutableString stringWithString: @"李刚"];
    t.age = 40;
    t.className = @"English";
    
    [NSKeyedArchiver archiveRootObject:t toFile:_file];
    
    // 读取
    Teacher *t = [NSKeyedUnarchiver unarchiveObjectWithFile:_file];
    
    • 实现NSCoding协议
      需要实现两个方法
      - (void)encodeWithCoder:(NSCoder *)aCoder;
      - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder;
    - (instancetype)initWithCoder:(NSCoder *)aDecoder {
        self = [super init];
        if (self) {
            self.name = [aDecoder decodeObjectOfClass:[NSMutableString class] forKey:NSStringFromSelector(@selector(name))];
            self.age = [[aDecoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(age))] unsignedIntegerValue];
            self.className = [aDecoder decodeObjectOfClass:[NSString class] forKey:NSStringFromSelector(@selector(className))];
        }
        return self;
    }
    
    - (void)encodeWithCoder:(NSCoder *)aCoder {
        [aCoder encodeObject:self.name forKey:NSStringFromSelector(@selector(name))];
        [aCoder encodeObject:[NSNumber numberWithUnsignedInteger:self.age] forKey:NSStringFromSelector(@selector(age))];
        [aCoder encodeObject:self.className forKey:NSStringFromSelector(@selector(className))];
    }
    

    NSSecureCoding

    • 简介
      NSSecureCoding是NSCoding的变种,因为NSCoding毕竟不太安全,大部分支持NSCoding的系统对象都已经升级到支持NSSecureCoding了,如AFNetworking的AFURLSessionManager

    未完待续

    相关文章

      网友评论

          本文标题:iOS NSCoding 与 NSSecureCoding

          本文链接:https://www.haomeiwen.com/subject/xxzwxftx.html