1.比较
在使用plist进行数据存储和读取,只适用于系统自带的一些常用类型才能用,且必须先获取路径;
NSUserDefaults 偏好设置(将所有的东西都保存在同一个文件夹下面,且主要用于存储应用的设置信息)归档:因为前两者都有一个致命的缺陷,只能存储常用的类型。归档可以实现把自定义的对象存放在文件中。
2.归档的使用
Archiving: 归档(写 NSKeyedArchiver )/解档(读NSKeyedUnarchiver): 从内存写到沙盒文件 从沙盒读取到内存中
前提:必须遵守 NSCoding协议才可以归档方式
1.适用场景 :
a。支持基本数据类型
b。自定义类型(比如实例变量、xib也默默的归档)
归档 5步骤,解档 4步骤
a.对基本类型的归档
- (NSString *)archivingFilePath { if (!_archivingFilePath) { NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; _archivingFilePath = [documentsPath stringByAppendingPathComponent:@"archiving"]; } return _archivingFilePath;}- (IBAction)writeNSArrayByArchiving:(id)sender { //准备数据 NSArray *array = @[@"name", @"age"]; NSArray *stuArray = @[@"Jonny", @19, @[@"Objective-C", @"Ruby"]]; //1.准备存储归档数据的可变数据类型 NSMutableData *mutableData = [NSMutableData data]; NSLog(@"归档前数据长度:%lu", (unsigned long)mutableData.length); //2.创建NSKeyedArchiver对象 写到mutableData里面 NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:mutableData]; //3.对要归档的数据进行编码操作(二进制) [archiver encodeObject:array forKey:@"firstArray"]; [archiver encodeObject:stuArray forKey:@"secondArray"]; //4.完成编码操作 [archiver finishEncoding]; NSLog(@"归档之后的数据长度:%lu", (unsigned long)mutableData.length); //5.将编码后的数据写到文件中 [mutableData writeToFile:self.archivingFilePath atomically:YES]; }- (IBAction)readDataByUnarchiving:(id)sender { //1.从文件中读取数据(NSData) NSData *data = [NSData dataWithContentsOfFile:self.archivingFilePath]; //2.创建NSKeyedUnarchiver对象 读取Data NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; //3.对数据进行解码操作 NSArray *firstArray = [unarchiver decodeObjectForKey:@"firstArray"]; NSArray *secondArray = [unarchiver decodeObjectForKey:@"secondArray"]; //4.完成解码操作 [unarchiver finishDecoding]; //验证 NSLog(@"firstArray:%@; secondArray:%@", firstArray, secondArray);}
2.对自定义类型的归档
- (void)viewDidLoad { [super viewDidLoad];//将自定义的类对象进行归档 (写) //1.可变数据 NSMutableData* data = [[NSMutableData alloc]init]; //2.归档对象 Person* person = [[Person alloc]initWithName:@"Jackey" age:@20]; //3.编码 NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data]; [archiver encodeObject:person forKey:@"person"];// 4.编码结束 [archiver finishEncoding];// 5.写入文件 NSString* docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject; NSString* filePath = [docPath stringByAppendingPathComponent:@"archiving"]; [data writeToFile:filePath atomically:YES]; // 将自定义的类对象进行解档 (读) //1.从文件中读取到数据(NSData) NSData* readData = [NSData dataWithContentsOfFile:filePath]; //2.创建NSKeyedUnarchiver对象 NSKeyedUnarchiver* unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:readData]; //3.对数据进行解码操作 Person* p = [unarchiver decodeObjectForKey:@"person"]; //4.完成解码操作 [unarchiver finishDecoding]; NSLog(@"person name:%@ --- age:%@",p.name,p.age); }