iOS Developer程序员

OC归档

2016-10-26  本文已影响0人  wlwl123

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"];
}```
#####解档方法
上一篇下一篇

猜你喜欢

热点阅读