本文主要是介绍ArchiverDemo(两种归档的方法),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
/*****************************第一种归档方法*******************************/
// 这种归档的缺点是 归档一个对象就对应一个文件 多个对象就会又多个文件
//
// //将一个数组归档
// NSArray *array = @[@"abc",@"123",@456];
// //根路径
// NSString *homePath = NSHomeDirectory();
// //创建一个新的路径 文件名的后缀可以随便 只是文件名的一部分
// NSString *filePath = [homePath stringByAppendingPathComponent:@"/arc.archive"];
// //判断归档是不是成功
// BOOL success = [NSKeyedArchiver archiveRootObject:array toFile:filePath];
//
// if (success)
// {
// NSLog(@"archive success");
// }
//
//
//
// //解归档
// NSString *homePath = NSHomeDirectory();
// NSString *filePath = [homePath stringByAppendingPathComponent:@"/arc.archive"];
// NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
// NSLog(@"%@",array);\
/*****************************第二种归档方法*******************************/
// //自定义内容的归档
// //创建一个可变data 给归档对象
// NSMutableData *data = [NSMutableData data];
// NSString *homePath = NSHomeDirectory();
// NSString *filePath = [homePath stringByAppendingPathComponent:@"archiver2.arc"];
// NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
// //将不同的数据类型归档
// [archiver encodeObject:@[@"123",@"asd",@34] forKey:@"array"];
// [archiver encodeFloat:23.7 forKey:@"float"];
// //调用下边的方法 将数据传到data里边
// [archiver finishEncoding];
// [archiver release];
// //将文件写入路径 并判断是否成功
// BOOL success = [data writeToFile:filePath atomically:YES];
// if (success)
// {
// NSLog(@"archive success");
// }
//解归档
NSString *homePath = NSHomeDirectory();
NSString *filePath = [homePath stringByAppendingPathComponent:@"archiver2.arc"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
NSArray *array = [unArchiver decodeObjectForKey:@"array"];
float f = [unArchiver decodeFloatForKey:@"float"];
[unArchiver release];
NSLog(@"array = %@ f = %f",array,f);
}
return 0;
}
这篇关于ArchiverDemo(两种归档的方法)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!