标签:blog http io 使用 ar for 文件 数据 2014
对象归档?就是把对象的数据保存成文件实现数据的加密(即在文档中不是明文显示)和永久储存。
需要使用时,则从文件中恢复即可。
(1)标准的数据
//main.m文件
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
//把一个数组进行归档
//创建一个文件路径
NSString *homePath=NSHomeDirectory();
NSString *filePath=[homePath stringByAppendingPathComponent:@"test.archive"];//后缀也可以是.arc
//创建个准备归档的数组
NSArray *arr1=@[@"111",@"222",@"333"];
BOOL success=[NSKeyedArchiver archiveRootObject:arr1 toFile:filePath];
if (success) {
NSLog(@"success");
}
//从归档文件中恢复数据
NSArray *arr2=[NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"%@",arr2);
}
return 0;
}
解归档,就是输出了数组的结果:
(
111,
222,
333
)//main.m文件
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
//创建一个文件路径
NSString *homePath=NSHomeDirectory();
NSString *filePath=[homePath stringByAppendingPathComponent:@"custom.arc"];
NSMutableData *data1=[NSMutableData data];//创建一个数据对象
NSKeyedArchiver *arc1=[[NSKeyedArchiver alloc]initForWritingWithMutableData:data1];//以data数据对象创建一个归档对象
[arc1 encodeObject:@"jack" forKey:@"name"];//把数据写入到归档文件中,即data中
[arc1 encodeFloat:50 forKey:@"weight"];
[arc1 finishEncoding];//结束写入数据
[data1 writeToFile:filePath atomically:YES];//把数据对象写入归档文件中
//先用数据对象把这个文件接下来
NSData *data2=[NSData dataWithContentsOfFile:filePath];
//再利用这个数据对象创建个解归档对象
NSKeyedUnarchiver *unarc1=[[NSKeyedUnarchiver alloc] initForReadingWithData:data2];
//利用解归档对象提取里面值
float weight1=[unarc1 decodeFloatForKey:@"weight"];
NSString *name1=[unarc1 decodeObjectForKey:@"name"];
NSLog(@"%.0f,%@",weight1,name1);
}
return 0;
}文件归档的效果:
解归档的输出结果:
50,jack
【OC学习-27】对象的归档以及解归档——标准数据和自定义数据的例子
标签:blog http io 使用 ar for 文件 数据 2014
原文地址:http://blog.csdn.net/weisubao/article/details/39137827