iOS应用数据存储的常用方式:
 1.XML属性列表     (plist归档)
 2.NSUserDefaults  (偏好设置)
 3.NSKeyedArchiver  归档(加密形式)
 4.SQLite3     (嵌入式数据库)
 5.Core Data    (面向对象方式的嵌入式数据库)
 
 
一.应用沙盒
 
1.iOS应用程序只能在为该改程序创建的文件系统中读取文件,不可以去其它地方访问,此区域被成为沙盒
  说明:
    a.每个应用程序都有自己的存储空间
    b.应用程序无法翻过自己的围墙去访问别的存储空间的内容
    c.应用程序请求的数据都要通过权限检测,假如不符合条件的话,不会被放行。
 
2.mac下查看沙盒路径
  step1.显示Mac隐藏文件的命令:defaults write com.apple.finder AppleShowAllFiles -bool true
  step2.进入如下路径/Users/username/Library/Application Support/iPhone Simulator/,即可找到各个程序的应用沙盒
 
3.沙盒目录结构
     默认情况下,每个程序的沙盒含有3个文件夹:Documents, Library 和 tmp:
    

  Documents:保存应用运行时生成的需要持久化的数据。例如,游戏应用可将游戏存档保存在该目录。iTunes同步设备时会备份该目录

  Library/Preference:保存应用的所有偏好设置,iOS的Settings(设置)应用会在该目录中查找应用的设置信息。iTunes同步设备时会备份该目录

  Library/Caches:保存应用运行时生成的需要持久化的数据,一般存储体积大、不需要备份的非重要数据,iTunes同步设备时不会备份该目录。

  tmp:保存应用运行时所需的临时数据,使用完毕后再将相应的文件从该目录删除。应用没有运行时,系统也可能会清除该目录下的文件。iTunes同步设备时不会备份该目录

4.获取目录路径代码:

  1. //获取沙盒路径
  2. NSString *home = NSHomeDirectory();
  3.  
  4. //1.获取Document路径
  5. //1.1通过文件名获取,因为ios以后的新版本可能修改目录名,不建议使用
  6. NSString *documentPath1 = [home stringByAppendingPathComponent:@"Documents"];
  7. //1.2通过系统方法获取,建议使用
  8. NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  9. NSString *documentPath2 = [array objectAtIndex:];
  10.  
  11. //2.获取Library/Cache目录,获取方式同Document,下面是系统方法
  12. NSArray *cache = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  13. NSString *cachePath = [cache objectAtIndex:];
  14.  
  15. //3.获取Library/Preferences也可食用1.1的方式获取,但因为是保存setting设置,一般通过NSUserDefaults直接存储
  16. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  17. [defaults setObject:@"myname" forKey:@"username"];
  18.  
  19. //4.获取tmp目录
  20. NSString *tmpPath = NSTemporaryDirectory();

如何在沙盒中操作文件夹和文件,系统提供了

二.文件存储

1.XML属性列表(plist归档)

  如果对象是NSString、NSDictionary、NSArray、NSData、NSNumber等类型,就可以使用writeToFile:atomically:方法直接将对象写到属性列表文件中,使用

dataWithContentsOfFile方法读取plist文件中的信息并实例化对象

  1. NSString *tmpPath = NSTemporaryDirectory();
  2. NSString *path = [tmpPath stringByAppendingPathComponent:@"test.plist"];
  3.  
  4. // 将数据封装成字典
  5. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  6. [dict setObject:@"jason" forKey:@"name"];
  7. [dict writeToFile:path atomically:YES];
  8.  
  9. // 读取plist的内容,实例化NSDictionary
  10. NSDictionary *dictPlist = [NSDictionary dictionaryWithContentsOfFile:path];
  11. NSLog(@"name:%@", [dictPlist objectForKey:@"name"]);

2.NSUserDefaults(偏好设置)

  使用set方法保存不同类型的对象,使用xxxForKey方法获取值

  1. //偏好设置
  2. NSUserDefaults *dft = [NSUserDefaults standardUserDefaults];
  3. [dft setObject:@"jason" forKey:@"username"];
  4. [dft setFloat:1.77f forKey:@"high"];
  5. [dft setBool:YES forKey:@"auto_logon"];
  6.  
  7. //读取偏好设置
  8. NSUserDefaults *dft2 = [NSUserDefaults standardUserDefaults];
  9. NSString *name = [dft2 objectForKey:@"username"];
  10. float h = [dft2 floatForKey:@"high"];
  11. BOOL al = [dft2 boolForKey:@"auto_logon"];
  12. NSLog(@"%@--%f--%hhd",name,h,al);

  自动在Library/Preferences/生成项目名开头的plist文件

  

3.NSKeyedArchiver  归档(加密形式)

  机制类似于java的对象序列化,归档是指将对象保存到文件,反归档(读档)是指将文件内容解析成对象

  3.1 NSString、NSDictionary、NSArray、NSData、NSNumber等类型,可以直接用NSKeyedArchiver进行归档和反归档

  3.2 任何遵守了NSCoding协议的对象,都可以进行归档和反归档

  3.3 NSCoding协议需要实现两个方法:
    - (void)encodeWithCoder:(NSCoder *)encoder //将对象归档的时候会调用(将对象写入文件之前会调用),用来说明哪些属性需要归档,怎样归档

    -(id)initWithCoder:(NSCoder *)decoder //当从文件中反归档对象时调用,用来说明哪些属性需要反归档,怎样反归档

    注:如果父类中也有属性需要归档或者反归档,必须调用super的encodeWithCoder:和initWithCoder:方法

  3.4代码实例:

    3.4.1 对象类:Person和子类Man

  1. // Person.h
  2. #import <Foundation/Foundation.h>
  3.  
  4. @interface Person : NSObject<NSCoding>
  5. @property (nonatomic, copy) NSString *name;
  6. @property (nonatomic, assign) int age;
  7. @property (nonatomic, assign) double height;
  8. @end
  9.  
  10. // Person.m
  11.  
  12. #import "Person.h"
  13.  
  14. @implementation Person
  15.  
  16. //归档时调用
  17. - (void)encodeWithCoder:(NSCoder *)coder
  18. {
  19. [coder encodeObject:_name forKey:@"name"];
  20. [coder encodeInt:_age forKey:@"age"];
  21. [coder encodeDouble:_height forKey:@"height"];
  22. }
  23.  
  24. //反归档时调用调用的初始化方法
  25. -(id)initWithCoder:(NSCoder *)deCode
  26. {
  27. if (self = [super init]) {
  28. _name = [deCode decodeObjectForKey:@"name"];
  29. _age = [deCode decodeIntForKey:@"age"];
  30. _height = [deCode decodeDoubleForKey:@"height"];
  31. }
  32. return self;
  33. }
  34.  
  35. @end
  36.  
  37. // Man.h继承自Person
  38. #import "Person.h"
  39.  
  40. @interface Man : Person
  41. @property (nonatomic, copy) NSString *sex;
  42. @end
  43.  
  44. // Man.m
  45. #import "Man.h"
  46.  
  47. @implementation Man
  48.  
  49. //归档时调用
  50. -(void)encodeWithCoder:(NSCoder *)coder
  51. {
  52. //首先调用父类的归档方法
  53. [super encodeWithCoder:coder];
  54. [coder encodeObject:_sex forKey:@"sex"];
  55. }
  56.  
  57. //反归档时调用的初始化方法
  58. -(id)initWithCoder:(NSCoder *)deCode
  59. {
  60. if (self = [super initWithCoder:deCode]) {
  61. _sex = [deCode decodeObjectForKey:@"sex"];
  62. }
  63. return self;
  64. }
  65.  
  66. @end

    3.4.1 归档和反归档的实现方法

  1. NSString *tmpPath = NSTemporaryDirectory();
  2. NSString *path1 = [tmpPath stringByAppendingPathComponent:@"person.data"];
  3. NSString *path2 = [tmpPath stringByAppendingPathComponent:@"man.data"];
  4.  
  5. Person *p = [[Person alloc]init];
  6. p.name = @"a";
  7. p.age = ;
  8. p.height = 1.70f;
  9.  
  10. Man *m = [[Man alloc]init];
  11. m.name = @"b";
  12. m.age = ;
  13. m.height = 1.77f;
  14. m.sex = @"male";
  15.  
  16. //归档
  17. [NSKeyedArchiver archiveRootObject:p toFile:path1];
  18. [NSKeyedArchiver archiveRootObject:m toFile:path2];
  19.  
  20. //反归档
  21. Person *p2 = [NSKeyedUnarchiver unarchiveObjectWithFile:path1];
  22. Man *m2 = [NSKeyedUnarchiver unarchiveObjectWithFile:path2];
  23. NSLog(@"%@--%d--%f",p2.name,p2.age,p2.height);
  24. NSLog(@"%@--%d--%f---%@",m2.name,m2.age,m2.height,m2.sex);

4.SQLite3 & Core Data

  都是对数据做操作,CoreData只是在SQLite3的基础上做了一层面向对象的封装,类似于Hibernate,暂不总结,后续会新写文章总结

三.NSFileManager

参考文章:http://www.cnblogs.com/xyzlmn/p/3196930.html

创建文件夹:

  1. //创建文件夹
  2. -(void *)createDir{
  3. NSString *documentsPath =[self dirDoc];
  4. NSFileManager *fileManager = [NSFileManager defaultManager];
  5. NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];
  6. // 创建目录
  7. BOOL res=[fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];
  8. if (res) {
  9. NSLog(@"文件夹创建成功");
  10. }else
  11. NSLog(@"文件夹创建失败");
  12. }

创建文件

  1. //创建文件
  2. -(void *)createFile{
  3. NSString *documentsPath =[self dirDoc];
  4. NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];
  5. NSFileManager *fileManager = [NSFileManager defaultManager];
  6. NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];
  7. BOOL res=[fileManager createFileAtPath:testPath contents:nil attributes:nil];
  8. if (res) {
  9. NSLog(@"文件创建成功: %@" ,testPath);
  10. }else
  11. NSLog(@"文件创建失败");
  12. }

写数据到文件:

  1. //写文件
  2. -(void)writeFile{
  3. NSString *documentsPath =[self dirDoc];
  4. NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];
  5. NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];
  6. NSString *content=@"测试写入内容!";
  7. BOOL res=[content writeToFile:testPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
  8. if (res) {
  9. NSLog(@"文件写入成功");
  10. }else
  11. NSLog(@"文件写入失败");
  12. }

读文件数据:

  1. //读文件
  2. -(void)readFile{
  3. NSString *documentsPath =[self dirDoc];
  4. NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];
  5. NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];
  6. // NSData *data = [NSData dataWithContentsOfFile:testPath];
  7. // NSLog(@"文件读取成功: %@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
  8. NSString *content=[NSString stringWithContentsOfFile:testPath encoding:NSUTF8StringEncoding error:nil];
  9. NSLog(@"文件读取成功: %@",content);
  10. }

文件属性:

  1. //文件属性
  2. -(void)fileAttriutes{
  3. NSString *documentsPath =[self dirDoc];
  4. NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];
  5. NSFileManager *fileManager = [NSFileManager defaultManager];
  6. NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];
  7. NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:testPath error:nil];
  8. NSArray *keys;
  9. id key, value;
  10. keys = [fileAttributes allKeys];
  11. int count = [keys count];
  12. for (int i = 0; i < count; i++)
  13. {
  14. key = [keys objectAtIndex: i];
  15. value = [fileAttributes objectForKey: key];
  16. NSLog (@"Key: %@ for value: %@", key, value);
  17. }
  18. }

删除文件:

  1. //删除文件
  2. -(void)deleteFile{
  3. NSString *documentsPath =[self dirDoc];
  4. NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];
  5. NSFileManager *fileManager = [NSFileManager defaultManager];
  6. NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];
  7. BOOL res=[fileManager removeItemAtPath:testPath error:nil];
  8. if (res) {
  9. NSLog(@"文件删除成功");
  10. }else
  11. NSLog(@"文件删除失败");
  12. NSLog(@"文件是否存在: %@",[fileManager isExecutableFileAtPath:testPath]?@"YES":@"NO");
  13. }

遍历子文件夹:

  1.     NSString *home = NSHomeDirectory();
  1.     NSFileManager *fileManage = [NSFileManagerdefaultManager];
  1.     NSArray *file = [fileManage subpathsOfDirectoryAtPath: home error:nil];
  1.     NSLog(@"%@",file);
  1.     NSArray *files = [fileManage subpathsAtPath: home ];
  1.     NSLog(@"%@",files);
  1.  

数据持久化-存取方式总结&应用沙盒&文件管理NSFileManager的更多相关文章

  1. iOS路径沙盒文件管理(转载)

    iOS路径沙盒文件管理,看到博主总结的很好,转载过来,原文:http://www.aichengxu.com/view/35264 一.iOS中的沙盒机制 iOS应用程序只能对自己创建的文件系统读取文 ...

  2. NSFileManager(沙盒文件管理)数据持久化 <序列化与反序列化>

    iOS应用程序只能在为该改程序创建的文件中读取文件,不可以去其它地方访问,此区域被成为沙盒,所以所有的非代码文件都要保存在此,例如图像,图标,声音,映像,属性列表,文本文件等.       默认情况下 ...

  3. NSFileManager 沙盒文件管理

    文件夹创建,复制,移动,删除,检查是否存在,代码如下: 1.获取沙盒 document 路径,作为文件夹路径的基路径. NSString *document = NSSearchPathForDire ...

  4. 1211笔记关于//modal//更改窗口的根控制器//数据存取//Plist属性列表//-“沙盒机制”//plis属性列表//偏好设置//归档普通对象//联系人数据存储//协议与回调函数

    一.利用Modal形式展示控制器 1.如何展示// vc就是要展示的新控制器[self presentViewController:vc animated:YES completion:^{    N ...

  5. iOS数据持久化-OC

    沙盒详解 1.IOS沙盒机制 IOS应用程序只能在为该改程序创建的文件系统中读取文件,不可以去其它地方访问,此区域被成为沙盒,所以所有的非代码文件都要保存在此,例如图像,图标,声音,映像,属性列表,文 ...

  6. iOS 阶段学习第25天笔记(iOS沙盒机制介绍)

    iOS学习(OC语言)知识点整理 一.iOS沙盒机制介绍 1)概念: 每个ios应用都有自己的应用沙盒,应用沙盒就是文件系统目录,与其他应用放入文件 系统隔离,ios系统不允许访问 其他应用的应用沙盒 ...

  7. 沙盒SandBox

    每个App都有自己的沙盒,也就是一个存储空间.App之间没有权限访问对方的沙盒资源.沙盒的目录下有三个文件夹:Documents.Library.temp 目录结构 Documents:用于存储用户数 ...

  8. iOS8沙盒路径的变化

    iOS8中的的沙盒路径发生了变化 之前是这样的路径,通过NSHomedictionary()获取的家路径 /Users/wupeng/Library/Application Support/iPhon ...

  9. iOS开发——数据持久化Swift篇&(二)沙盒文件

    沙盒文件 //******************** 5.2 文件操作 func use_FileOperations() { //1.获取程序的Home目录 let homeDirectory = ...

随机推荐

  1. Elasticsearch中的CRUD

    在<玩玩儿Elasticsearch>中简介了一下elasticsearch.这篇文章.我们还是做些基础的学习.在Elasticsearch怎样进行CRUD? 如果我们正在创建的一个类似微 ...

  2. Spring深入浅出(四)AOP面向切面

    面向切面编程--AOP AOP(Aspect Oriented Programming),程序员称之为面向切面编程,是Spring框架除了IOC之外的另一个核心概念. AOP是对OOP(面向对象编程) ...

  3. python 3.x 学习笔记5 (装饰器)

    1.装饰器: 本质是函数,(装饰其他函数)就是为其他函数添加附加功能 原则: 1)不能修改被装饰的函数的源代码 2)不能修改被装饰的函数的调用方式 2.实现装饰器知识储备: 1)函数即“变量” 2)高 ...

  4. Android属性动画-基本用法

    在手机上去实现一些动画效果算是件比较炫酷的事情,因此Android系统在一开始的时候就给我们提供了两种实现动画效果的方式,逐帧动画(frame-by-frame animation)和补间动画(twe ...

  5. 高德地图和canvas画图结合应用(二)

    上节讲述了如在在高德地图中添加canvas图层,这节就讲述下如何在canvas图层添加鼠标的事件. 在上节脚本的最后加入以下代码: var text; $('#container').on('clic ...

  6. PostgreSQL Replication之第四章 设置异步复制(5)

    4.5 使流复制更健壮 当连接到master时,slave要做的第一件事情是赶上master.但是,这会一直工作吗?我们已经看到,我们可以使用由基于流和基于文件组成的混合设置.这给了我们一些额外的安全 ...

  7. Bayes++ Library入门学习之熟悉class-Bayesian_filter_base(2)

    前面我们已经熟悉了Bayesian_filter::Bayes_filter_base和其子类的击继承关系,接下来我们开始学习该类的实现. bayesFlt.hpp文件为其实现主体,首先是两个常规的头 ...

  8. windows, fast-rcnn CPU版本的安装配置

    一:安装准备 1:caffe的安装配置,本人用的是happynear大神的caffe版本,具体链接https://github.com/happynear/caffe-windows,编译时需要用到p ...

  9. ORM原理

    原理: 1.实现JavaBean的属性到数据库表的字段的映射:        --通过配置文件将JavaBean的属性与数据库表的字段的关联起来 2.映射关系:   一对多,多对一等 持久层(Pers ...

  10. ES6学习笔记(十二)异步解决方案Promise

    1.Promise 的含义 Promise 是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大.它由社区最早提出和实现,ES6 将其写进了语言标准,统一了用法,原生提供了P ...