●沙盒根目录:NSString *home =NSHomeDirectory();●Documents:(2种⽅方式)
●利用沙盒根目录拼接”Documents”字符串
NSString *home =NSHomeDirectory();
NSString *documents = [homestringByAppendingPathComponent:@"Documents"];//不建议采用,因为新版本的操作系统可能会修改目录名
●利⽤NSSearchPathForDirectoriesInDomains函数
// NSUserDomainMask代表从用户文件夹下找
// YES代表展开路径中的波浪字符“~”
NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, NO); //在iOS中,只有一个目录跟传入的参数匹配,所以这个集合里面只有一个元素
NSString *documents = [array objectAtIndex:0];
●tmp:NSString *tmp =NSTemporaryDirectory();
●Library/Caches:(跟Documents类似的2种⽅方法)
●利用沙盒根目录拼接”Caches”字符串
●利⽤NSSearchPathForDirectoriesInDomains函数(将函数的第2个参数改 为:NSCachesDirectory即可)
●Library/Preference:通过NSUserDefaults类存取该目录下的设置信息
相应的代码:
1 #import "NJViewController.h"2 #import "NJPerson.h"3 4 @interface NJViewController ()5 - (IBAction)saveDataBtnClick:(id)sender;6 - (IBAction)readDataBtnClick:(id)sender;7 8 @end9 10 @implementation NJViewController11 /**12 * 点击保存按钮13 */14 - (IBAction)saveDataBtnClick:(id)sender {1516// youtube做法17 // NSString *path = @"/Users/apple/Library/Application Support/iPhone Simulator/7.1/Applications/A6D53E11-DDF0-4392-B2D4-FE77A96888A6/Documents/abc.plist";1819// 获取应用程序根目录20NSString *home = NSHomeDirectory();2122// 不建议写/23//NSString *path = [home stringByAppendingString:@"/Documents"];24// 不建议Documents写死25//NSString *path = [home stringByAppendingPathComponent:@"Documents"];2627// NSUserDomainMask 在用户目录下查找28// YES 代表用户目录的~29// NSDocumentDirectory 查找Documents文件夹30// 建议使用如下方法动态获取31NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];32// 拼接文件路径33NSString *path = [doc stringByAppendingPathComponent:@"abc.plist"];34NSLog(@"%@", path);353637//NSArray *arr = @[@"lnj", @"28"];38//[arr writeToFile:path atomically:YES];3940// NSDictionary *dict = @{@"name": @"lnj", @"age":@"28"};41// 调用writeToFile将数据写入文件42// [dict writeToFile:path atomically:YES];4344/*45plist只能存储系统自带的一些常规的类, 也就是有writeToFile方法的对象才可以使用plist保存数据46字符串/字典/数据/NSNumber/NSData ...47*/4849// 自定义的对象不能保存到plist中50NJPerson *p = [[NJPerson alloc] init];51p.name =@"lnj";5253NSDictionary *dict = @{@"person": @"abc"};54[dict writeToFile:path atomically:YES];55 }56 /**57 * 点击读取按钮58 */59 - (IBAction)readDataBtnClick:(id)sender {60NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];6162NSString *path = [doc stringByAppendingPathComponent:@"abc.plist"]63;64// 读取数据65NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];66NSLog(@"%@", dict);67 }68 @end
五、属性列表
●属性列表是一种XML格式的文件,拓展名为plist
●如果对象是NSString、NSDictionary、NSArray、NSData、NSNumber等类型,就可以使用writeToFile:atomically:⽅法 直接将对象写到属性列表文件中