美文网首页
数据存储,model 对象归档本地化

数据存储,model 对象归档本地化

作者: seventhboy | 来源:发表于2018-03-01 10:52 被阅读20次
    • (IBAction)saveBtnOnclick:(UIButton *)sender {
      Student *student=[[Student alloc]init];
      student.name=@"bp";
      student.age=25;
      student.height=1.9;
      student.weight=62;

      //获取文件路径
      NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
      NSString *path=[docPath stringByAppendingPathComponent:@"student.bp"];

      //将自定义的对象保存到文件
      [NSKeyedArchiver archiveRootObject:student toFile:path];
      }

    • (IBAction)readBtnOnclick:(UIButton *)sender {
      NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
      NSString *path=[docPath stringByAppendingPathComponent:@"student.bp"];

      //从文件中读取对象
      Student *student=[NSKeyedUnarchiver unarchiveObjectWithFile:path];
      NSLog(@"%@ %D %.1f %f",student.name,student.age,student.height,student.weight);
      }

    -(void)encodeWithCoder:(NSCoder *)aCoder
    {
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeInteger:self.age forKey:@"age"];
    [aCoder encodeDouble:self.height forKey:@"height"];
    [aCoder encodeFloat:self.weight forKey:@"weight"];
    }
    -(id)initWithCoder:(NSCoder *)aDecoder
    {
    if (self=[super init]) {
    self.name=[aDecoder decodeObjectForKey:@"name"];
    self.age=[aDecoder decodeIntegerForKey:@"age"];
    self.height=[aDecoder decodeDoubleForKey:@"height"];
    self.weight=[aDecoder decodeFloatForKey:@"weight"];
    }
    return self;
    }

    相关文章

      网友评论

          本文标题:数据存储,model 对象归档本地化

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