IOS 开发之数据存储writeToFile的应用实例

时间:2022-11-30 20:17:19

IOS 开发之数据存储writeToFile的应用实例

最近项目上要弄数据的导入与导出,所以就研究了一下数据的保存,其实很简单

 第一步:获得文件即将保存的路径:

NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask,YES);//使用C函数NSSearchPathForDirectoriesInDomains来获得沙盒中目录的全路径。该函数有三个参数,目录类型、he domain mask、布尔值。其中布尔值表示是否需要通过~扩展路径。而且第一个参数是不变的,即为NSSearchPathDirectory 。在iOS中后两个参数也是不变的,即为:NSUserDomainMask 和 YES。

?
1
NSString *ourDocumentPath =[documentPaths objectAtIndex:0];

还有一种方法是使用NSHomeDirectory函数获得sandbox的路径。具体的用法为:

?
1
NSString *sandboxPath = NSHomeDirectory();

// Once you have the full sandbox path, you can create a path from it,但是不能在sandbox的本文件层上写文件也不能创建目录,而应该是此基础上创建一个新的可写的目录,例如Documents,Library或者temp。

?
1
2
NSString *documentPath = [sandboxPath
      stringByAppendingPathComponent:@"Documents"];//将Documents添加到sandbox路径上,具体原因前面分析了!

这两者的区别就是:使用NSSearchPathForDirectoriesInDomains比在NSHomeDirectory后面添加Document更加安全。因为该文件目录可能在未来发送的系统上发生改变。  

第二步:生成在该路径下的文件:

?
1
NSString *FileName=[documentPath stringByAppendingPathComponent:fileName];//fileName就是保存文件的文件名

第三步:往文件中写入数据:

?
1
[data writeToFile:FileName atomically:YES];//将NSData类型对象data写入文件,文件名为FileName

最后:从文件中读出数据:

?
1
NSData *data=[NSData dataWithContentsOfFile:FileName options:0 error:NULL];//从FileName中读取出数据

以上就是IOS 开发之数据存储writeToFile的应用实例,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://wy19921005.iteye.com/blog/2391847