首先我们来认识一下沙盒,沙盒就是每一个app对应的一块存储空间。
沙盒中有下列文件夹
Documents:文档 最常打交道的目录 iTunes会备份和恢复此文件夹的内容
Library/Caches : 缓存文件夹 用来保存缓存数据 不会备份和恢复
Library/Preferences:用户偏好设置 iTunes会备份和恢复此文件夹的内容
tmp:临时文件夹 存放临时文件 不会备份和恢复 此文件夹内容会不定时清除
下面我们通过代码来看一下沙盒的使用
NSString *homePath = NSHomeDirectory();
NSLog(@"沙箱根目录:%@",homePath);
//获取Documents路径两种方法
NSString *documentsPath1 = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *documentsPath2 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
NSLog(@"%@ %@",documentsPath1,documentsPath2);
//获取缓存文件夹路径
NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];
//获取临时文件夹路径
NSString *tmpPath = NSTemporaryDirectory();
NSLog(@"缓存:%@ 临时:%@",cachePath,tmpPath);
//往document中写.txt
NSString *text = @"过年好!";
NSString *path = [documentsPath1 stringByAppendingPathComponent:@"abc.txt"];
[text writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
//往document中写.plist plist中存放数组
NSString *filePath = [documentsPath1 stringByAppendingPathComponent:@"names.plist"];
NSArray *names = @[@"a",@"b",@"c"];
[names writeToFile:filePath atomically:YES];
输出结果如下:
下面我们复制documents的地址,通过finder前往当前目录,看一下plist文件,还有txt文件是否写入。结果如图:
对于plist文件读写,还有不理解的朋友请参考这篇微博:
http://blog.youkuaiyun.com/lee727n/article/details/70303766