美文网首页
iOS 归档

iOS 归档

作者: 冰点雨 | 来源:发表于2020-10-29 16:35 被阅读0次

    写入数据

    //1.文件路径    
        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"info.plist"];       
    //1. 有个对象
        Student *student = [[Student alloc]init];
        student.name = @"11";    
        student.age = 10;          
    //2.存储  归档    
        [NSKeyedArchiver archiveRootObject:student toFile:path];
    

    读取数据

      NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"info.plist"];       
    //反归档 ,解档
        Student *p = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    

    注意:
    如果使用归档

    1. 该对象必须遵守NSCoding 协议 编码协议
    2. 实现 encodeWithCoder方法
    3. 实现:initWIthCoder方法

    实现<NSCoding>协议方法

    - (void)encodeWithCoder:(NSCoder *)coder{
       [coder encodeObject:self.name forKey:@"name"];
       [coder encodeInteger:self.age forKey:@"age"];
       
    }
    //反归档只是个过程, 告诉系统你读取的时候,想让别人读取哪些属性
    - (instancetype)initWithCoder:(NSCoder *)decoder{
        if (self = [super init]) {
            self.name = [decoder decodeObjectForKey:@"name"];
            self.age  = [decoder decodeIntegerForKey:@"age"];
         }
         return self;
    }
    

    相关文章

      网友评论

          本文标题:iOS 归档

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