美文网首页
NSCoding 的使用

NSCoding 的使用

作者: 狒狒James_Leo | 来源:发表于2018-01-03 09:35 被阅读0次

    定义一个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];

    相关文章

      网友评论

          本文标题:NSCoding 的使用

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