iOS NSCoding 与 NSSecureCoding

2018-03-01  本文已影响65人  iOS_肖晨

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];
- (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

未完待续

上一篇下一篇

猜你喜欢

热点阅读