NSCoding 的使用

2018-01-03  本文已影响0人  狒狒James_Leo

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

@interface MyModel:NSObject<NSCoding>
@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];
上一篇下一篇

猜你喜欢

热点阅读