- OC的序列化和反序列化就是用来存储对象和访问对象。
- 序列化就是通过归档把对象转化成二进制文件。
- 反序列化就是通过解档把二进制转化成对象。
直接上代码
-
1.首先我们创建一个工程,新建一个OneTest类继承NSObjct
-
2.在OneTest类 .h里面实现<NSCoding>协议 设置name, sex,age三个属性(随便写)。
- 3.在ViewController的viewDidLoad方法创建俩个button(一个存,一个取)。
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
saveBtn.frame = CGRectMake(50, 50, 120, 40);
saveBtn.backgroundColor = [UIColor orangeColor];
[saveBtn setTitle:@"归档(存储)" forState:UIControlStateNormal];
[saveBtn addTarget:self action:@selector(saveGD:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:saveBtn];
UIButton *takeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
takeBtn.frame = CGRectMake(50, 120, 120, 40);
takeBtn.backgroundColor = [UIColor orangeColor];
[takeBtn setTitle:@"解档(取出)" forState:UIControlStateNormal];
[takeBtn addTarget:self action:@selector(takeJD:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:takeBtn];
}
button调用的方法(获取沙盒路径文章最后有)
// 归档
- (void)saveGD:(UIButton *)sender{
//在这里我们模拟数据归档
OneTest *oneTest = [[OneTest alloc] init];
oneTest.nameStr = @"浮生若梦";
oneTest.sexStr = @"男";
oneTest.age = 18;
//设置一个保存路径
//获取Document文件路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths objectAtIndex:0];
NSLog(@"path====:%@",documentPath);
NSString *filePath = [documentPath stringByAppendingPathComponent:@"chang"];
//归档
[NSKeyedArchiver archiveRootObject:oneTest toFile:filePath];
}
//解档
- (void)takeJD:(UIButton *)sender{
//获取Document文件路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths objectAtIndex:0];
NSLog(@"path====:%@",documentPath);
NSString *filePath = [documentPath stringByAppendingPathComponent:@"chang"];
//解档
OneTest *oneTest = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"名字==%@,性别==%@,年龄==%d",oneTest.nameStr,oneTest.sexStr,oneTest.age);
}
-
4.此时点击第一个归档存储
打印出的路径(复制前往路径)快捷键command+shift+g
-
5.此时点击第二个解档取出 控制台输出之前存储的内容
iOS归档和解档到此就完成了,是不是很简单啊。
- 获取沙盒中的路径方法:
//沙盒中会有三个文件夹,都是系统自动创建的
1、获取document目。Documents:这个目录用于存储用户数据。
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSLog(@"path:%@",path);
2、获取Caches目录。Library下的Caches文件夹用来存放缓存文件,iTunes不会备份此目录,此目录下文件不会在应用退出删除。
NSArray *pahts = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [pahts objectAtIndex:0];
NSLog(@"%@",path);
3、获取Library目录。Library:存储程序的默认设置或其它状态信息。
NSArray *pahts = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *path = [pahts objectAtIndex:0];
NSLog(@"%@",path);
4、获取temp目录。 tmp:提供一个即时创建临时文件的地方。
NSString *temDir = NSTemporaryDirectory();
NSLog(@"%@",temDir);