@SanMao
2015-12-19T14:47:13.000000Z
字数 2297
阅读 1383
文件存储
每个应用程序都有自己的应用沙盒(应用沙盒就是文件系统目录)应用程序必须待在自己的沙盒里,其他应用不能访问该沙盒
Documents:保存应用运行时生成的需要持久化的数据,iTunes同步设备时会备份该目录。例如,游戏应用可将游戏存档保存在该目录
tmp:保存应用运行时所需的临时数据,使用完毕后再将相应的文件从该目录删除。应用没有运行时,系统也可能会清除该目录下的文件。iTunes同步设备时不会备份该目录
Library/Caches:保存应用运行时生成的需要持久化的数据,iTunes同步设备时不会备份该目录。一般存储体积大、不需要备份的非重要数据
Library/Preference:保存应用的所有偏好设置,iOS的Settings(设置)应用会在该目录中查找应用的设置信息。iTunes同步设备时会备份该目录
NSString *home = NSHomeDirectory();
- (IBAction)save:(id)sender {// 确定数据将要存储的位置为cache文件夹// 获取cache文件夹的路径NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];// 拼接文件存储的全路径NSString *filePath = [cachePath stringByAppendingPathComponent:@"arr.plist"];// 存储文件// plist文件不能存储自定义对象[_arr writeToFile:filePath atomically:YES];}- (IBAction)read:(id)sender {// 获取cache文件夹的路径NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];// NSLog(@"%@",cachePath);// 拼接文件存储的全路径NSString *filePath = [cachePath stringByAppendingPathComponent:@"arr.plist"];// 读取文件首先要确定文件的类型(此处为数组)NSArray *arr = [NSArray arrayWithContentsOfFile:filePath];NSLog(@"%@",arr);}
- (IBAction)preferenceSave:(id)sender {// 快速存储键值对,不需要路径,系统会自动处理[[NSUserDefaults standardUserDefaults] setObject:@"张三" forKey:@"name"];[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"autoLogin"];}- (IBAction)preferenceRead:(id)sender {// 存的是什么类型,读取的就是什么类型NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"name"];// BOOL b = [[NSUserDefaults standardUserDefaults] boolForKey:@"autoLogin"];NSLog(@"%@",str);}
- (IBAction)saveDoc:(id)sender {// 自定义对象要保存到沙盒,必须通过归档Person *p = [[Person alloc] init];p.name = @"李四";p.age = 18;// 获取document文件夹路径NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];// 拼接全路径NSString *filePath = [documentPath stringByAppendingPathComponent:@"suibian.data"];// 归档的对象必须要遵守NSCoding协议,并实现encodeWithCoder: 方法(方法中主要是明确对象的哪些属性需要归档)[NSKeyedArchiver archiveRootObject:p toFile:filePath];}- (IBAction)readDoc:(id)sender {// 创建对象Person *p = [[Person alloc] init];// 加载document路径NSString *document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];// 拼接全路径NSString *filePath = [document stringByAppendingPathComponent:@"suibian.data"];// 解档p = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];NSLog(@"%@",p.name);}