1.比较 编码
在使用plist进行数据存储和读取,只适用于系统自带的一些经常使用类型才能用,且必须先获取路径;
NSUserDefaults 偏好设置(将全部的东西都保存在同一个文件夹下面,且主要用于存储应用的设置信息)atom
归档:由于前二者都有一个致命的缺陷,只能存储经常使用的类型。归档能够实现把自定义的对象存放在文件中。spa
2.归档的使用code
Archiving: 归档(写 NSKeyedArchiver )/解档(读NSKeyedUnarchiver): 从内存写到沙盒文件 从沙盒读取到内存中
orm
前提:必须遵照 NSCoding协议才能够归档方式对象
1.适用场景 :内存
a。支持基本数据类型ci
b。自定义类型(好比实例变量、xib也默默的归档)string
归档 5步骤,解档 4步骤it
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); }