NSCoding 的使用

定义一个Model,让其遵循NSCoding协议,方便我们进行归档数据存储(直接到plist或者NSUserdefaults)
OC

@interface MyModel:NSObject
@property (copy,nonatomic)NSString * name;
@property (nonatomic)int age;
@end

@implementation MyModel

-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super init]) {
        self.name = [aDecoder decodeObjectForKey:@"kName"];
        self.age = [aDecoder decodeInt32ForKey:@"kAge"];
    }
    return self;
}

-(void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:self.name forKey:@"kName"];
    [aCoder encodeInt32:self.age forKey:@"kAge"];
}
-(NSString *)description{
    return [NSString stringWithFormat:@"Name:%@; Age:%d",self.name,self.age];

你可能感兴趣的:(NSCoding 的使用)