博客> 归档解档的简单总结
归档解档的简单总结
2019-10-18 22:30 评论:0 阅读:802 默默besty

在项目中可以讲自定义对象持久化保存,mark一下我归档解档一个自定义对象 在模型层中使用 -(void)encodeWithCoder:(NSCoder )aCoder{}和 -(id)initWithCoder:(NSCoder)aDecoder{}

实现如下效果

1. -(void)encodeWithCoder:(NSCoder *)aCoder{ [aCoder encodeObject:self.ubm_id forKey:@"ubm_id"]; [aCoder encodeObject:self.createDate forKey:@"createDate"]; [aCoder encodeObject:self.email forKey:@"email"]; [aCoder encodeObject:self.nickname forKey:@"nickname"]; [aCoder encodeObject:self.password forKey:@"password"]; }

-(id)initWithCoder:(NSCoder*)aDecoder{

if (self ==[super init]) {
    self.ubm_id =[aDecoder decodeObjectForKey:@"ubm_id"];
    self.createDate =[aDecoder decodeObjectForKey:@"createDate"];
    self.email =[aDecoder decodeObjectForKey:@"email"];
    self.nickname =[aDecoder decodeObjectForKey:@"nickname"];
    self.password =[aDecoder decodeObjectForKey:@"password"];

}
return self;

}

2。然后在需要归档的地方进行如下操作 shareApp.loginUser = user;// 保存登录信息

    NSData * data =[NSKeyedArchiver archivedDataWithRootObject:user];
    NSUserDefaults *users = [NSUserDefaults standardUserDefaults];
    [users setObject:data forKey:@"userInfo"];

3.在解档的地方获取到数据 //获取数据 NSUserDefaults users =[NSUserDefaults standardUserDefaults]; NSData data =[users objectForKey:@"userInfo"]; self.loginUser =[NSKeyedUnarchiver unarchiveObjectWithData:data];

收藏
0
sina weixin mail 回到顶部