1、plist 文件的读写
读取:
1.创建plist文件: student.plist ;
2.创建数组用于储存plist绝对路径,并初始化; NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"student" ofType:@"plist"];
3.1 字典类型: ①创建字典并遍历,利用 objectForKey找到对应的值; for (NSDictionary *dic in array) { NSString *nameStr = [dic objectForKey:@"name”]; }
②创建字典并使用initWithContentsOfFile初始化; NSDictionary *dic = [[NSDictionary alloc]initWithContentsOfFile:self.plistStr];
3.2 数组类型: 创建数组并使用initWithContentsOfFile初始化; NSArray *array = [[NSArray alloc]initWithContentsOfFile:plistPath];
写入:
1.创建一个用于储存plist文件储存地址的路径(沙盒/Document/)的字符串; @property (nonatomic, strong) NSString *plistStr;
2.懒加载字符串,将用户文件与将要创建的plist文件路径拼接,获取绝对路径; _plistStr = [documentsPath stringByAppendingPathComponent:@"test.plist"];
3.创建要储存的文件,分为字典类型和数组类型; NSDictionary *dic = @{@"names":@[@"Test0",@"Test1"]};
4.将要储存的字典或数组写入带有绝对路径的文件; [dic writeToFile:self.plistStr atomically:YES];
2、归档文件
写入
1.准备储存归档数据的可变数据类型; NSMutableData *mutableData = [NSMutableData data];
2.创建NSKeyedArchiving对象; NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:mutableData];
3.对要归档的文件经行编码操作; [archiver encodeObject:array forKey:@"firstArray"];
4.完成编码操作; [archiver finishEncoding];
5.将编码后的数据写入到文件中; [mutableData writeToFile:self.archivingFilePath atomically:YES];
读取
1.从文件中读取数据(NSData); NSData *data = [NSData dataWithContentsOfFile:_archivingFilePath];
2.创建NSKeyedNarchiving对象; NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
3.对数据经行解码操作; NSArray *firstArray = [unarchiver decodeObjectForKey:@"firstArray"];
4.完成解码操作; [unarchiver finishDecoding];