归档 & 反归档

来源:互联网 发布:艾瑞社交数据研究报告 编辑:程序博客网 时间:2024/05/01 04:58

如果想要实现归档和反归档的操作需要签订一个协议 NSCoding


[NSKeyedArchiver archiveRootObject:stuArr toFile:documentPath]; // 归档(写入)


- (void)encodeWithCoder:(NSCoder *)aCoder { // 归档

    [aCoder encodeObject:self.name forKey:@"姓名"];

    [aCoder encodeObject:self.sex forKey:@"性别"];

    [aCoder encodeObject:self.hobby forKey:@"爱好"];

    [aCoder encodeInteger:self.age forKey:@"年龄"];

}


NSArray *studentArray = [NSKeyedUnarchiver unarchiveObjectWithFile:documentPath]; // 反归档(读取)

- (id)initWithCoder:(NSCoder *)aDecoder { // 反归档

    self = [super init];

    if (self) {

        self.name = [aDecoder decodeObjectForKey:@"姓名"];

        self.age = [aDecoder decodeIntegerForKey:@"年龄"];

        self.hobby = [aDecoder decodeObjectForKey:@"爱好"];

        self.sex = [aDecoder decodeObjectForKey:@"性别"];

    }

    return self;

}


存储与读取的两个button 的绑定方法

- (IBAction)save:(UIButton *)button {

    MSPersonModel *person = [MSPersonModel personWithName:@"唐启哲" age:19];

    

    NSString *rootPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];

    

    NSString *allPath = [rootPath stringByAppendingPathComponent:@"person.data"];

    

    [NSKeyedArchiver archiveRootObject:person toFile:allPath];

}



- (IBAction)read:(UIButton *)button {

    NSString *rootPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES)[0];

    

    NSString *allPath = [rootPath stringByAppendingPathComponent:@"person.data"];(若是person.plist文件 可加载一个数组)

    

    MSPersonModel *person = [NSKeyedUnarchiver unarchiveObjectWithFile:allPath];

    

    NSLog(@"%@ ---- %li", person.name, person.age);

}


0 0
原创粉丝点击