数据的序列化,持久化,归档
数据的序列化,持久化,归档
1.Foundation
2.数据属性列表(NSArray,NSDictionary)
3.sqlite,cocodata
归档后文件的数据会自动加密,不再是明文,局限性在于,只能对一个对象进行归档
/**归档,数据持久化,数据序列化**/
/*
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/text.arc"];
NSArray *array = @[@"jack",@"tom",@"dav",@123789];
BOOL success = [NSKeyedArchiver archiveRootObject:array toFile:filePath];
if (success) {
NSLog(@"文件归档成功!!!");
}
*/
/**解归档***/
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/text.arc"];
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"array :%@",array);
//对多个对象进行归档的,自定义方式
//----------------1.第二种归档--------------------------------
/*自定义归档**/
/*
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/coustom.archiver"];
NSMutableData *data = [NSMutableData data];
NSKeyedArchiver *archiverFile = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
NSArray *array = @[@"jack",@"tom"];
[archiverFile encodeInt:100 forKey:@"age"];
[archiverFile encodeObject:array forKey:@"name"];
[archiverFile finishEncoding];
[data writeToFile:filePath atomically:YES];
[archiverFile release];
*/
/**自定义解归档***/
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/coustom.archiver"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
int age = [unArchiver decodeIntForKey:@"age"];
NSArray *arrayName = [unArchiver decodeObjectForKey:@"name"];
[unArchiver release];
NSLog(@"age=%d,arrayName:%@",age,arrayName);
对象要实现归档则要实现代理<NSCoding>
//归档
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:_name forKey:NAME];
[aCoder encodeObject:_email forKey:EMAIL];
[aCoder encodeObject:_password forKey:PASSWORD];
[aCoder encodeInt:_age forKey:AGE];
}
//解档
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self != nil) {
_age = [aDecoder decodeIntForKey:AGE];
_name = [[aDecoder decodeObjectForKey:NAME] copy];
self.email = [aDecoder decodeObjectForKey:EMAIL];
self.password = [aDecoder decodeObjectForKey:PASSWORD];
}
return self;
}
-(NSString *)description
{
NSString *str = [NSString stringWithFormat:@"name==%@,age==%d,email==%@,password==%@",_name,_age,_email,_password];
return str;
}