OC归档

作者: wlwl123 | 来源:发表于2016-10-26 20:21 被阅读0次

    archive:归档
    主要是把对象 存 磁盘
    对象包括 系统对象 如 NSString NSArray NSDictionary
    特殊之处: 可以存储 自定类型的对象

    1. NSString 类型
    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject.
    NSLog(@"%@", docPath);
    NSString *strPath = [docPath stringByAppendingPathComponent:@"str"];
    //归档
    [NSKeyedArchiver archiveRootObject:@"你好" toFile:strPath];
    //解档
    NSString *str = [NSKeyedUnarchiver unarchiveObjectWithFile:strPath];
    NSLog(@"%@", str);```
    
    2. 字典类型
    
    //1. 拼接路径 ~/Documents/dic
    NSString *dicPath = [docPath stringByAppendingPathComponent:@"dic"];
    //2. 归档一个字典类型 到路径下
    //@{@"name":@"cheng", @"age":@18, @"skill":@"smile"}
    [NSKeyedArchiver archiveRootObject:@{@"name":@"cheng", @"age":@18, @"skill":@"smile"} toFile:dicPath];
    //3. 解档 并 打印
    NSDictionary *dic = [NSKeyedUnarchiver unarchiveObjectWithFile:dicPath];
    NSLog(@"%@", dic);```
    
    1. 自定义类型的 如对象
    Student *stu = [Student new];
        stu.name = @"Master.Cheng";
        stu.sex = @"women";
        stu.age = 22;
        stu.marry = NO;
        stu.school = @"山东蓝翔职业挖掘机技术学院";
        stu.className = @"挖掘机2班";
        stu.favor = @"虚空遁地兽";
        stu.skill = @"打野";
        stu.score = @"良+";
        NSString *stuPath = [docPath stringByAppendingPathComponent:@"stu"];
        [NSKeyedArchiver archiveRootObject:stu toFile:stuPath];
        Student *aaa = [NSKeyedUnarchiver unarchiveObjectWithFile:stuPath];
        NSLog(@"%@", aaa);
    

    自定义类型的注意点:
    对于自定义类型的归档, 必须实现 NSCoding协议
    并实现其中负责归档 和 解档的两个方法

    归档方法
     - (void)encodeWithCoder:(NSCoder *)aCoder{
         [aCoder encodeObject:_name forKey:@"name"];
         [aCoder encodeObject:_sex forKey:@"sex"];
         [aCoder encodeInteger:_age forKey:@"age"];
         [aCoder encodeBool:_marry forKey:@"marry"];
         [aCoder encodeObject:_skill forKey:@"skill"];
         [aCoder encodeObject:_school forKey:@"school"];
         [aCoder encodeObject:_score forKey:@"score"];
         [aCoder encodeObject:_className forKey:@"className"];
         [aCoder encodeObject:_favor forKey:@"favor"];
    }```
    #####解档方法
    
    • (instancetype)initWithCoder:(NSCoder *)aDecoder{
      if (self = [super init]) {
      self.name = [aDecoder decodeObjectForKey:@"name"];
      self.sex = [aDecoder decodeObjectForKey:@"sex"];
      self.age = [aDecoder decodeIntegerForKey:@"age"];
      self.skill = [aDecoder decodeObjectForKey:@"skill"];
      self.favor = [aDecoder decodeObjectForKey:@"favor"];
      self.className = [aDecoder decodeObjectForKey:@"className"];
      self.school = [aDecoder decodeObjectForKey:@"school"];
      self.score = [aDecoder decodeObjectForKey:@"score"];
      self.marry = [aDecoder decodeBoolForKey:@"marry"];
      }
      return self;
      }```

    相关文章

      网友评论

        本文标题:OC归档

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