1.

iPhone会为每一个应用程序生成一个私有目录,这个目录位于:

/Users/sundfsun2009/Library/Application Support/iPhone Simulator/User/Applications下,

并随即生成一个数字字母串作为目录名,在每一次应用程序启动时,这个字母数字串都是不同于上一次。

所以通常使用Documents目录进行数据持久化的保存,而这个Documents目录可以通过:

NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserdomainMask,YES) 得到。

代码如下:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSLog(@"path:   %@",path);

打印结果如下:

path:   /Users/apple/Library/Application Support/iPhone Simulator/4.3/Applications/550AF26D-174B-42E6-881B-B7499FAA32B7/Documents

而通过 NSHomeDirectory()也可以得到程序的目录,代码如下:

NSString *destPath = NSHomeDirectory();

NSLog(@"path:   %@",destPath);

打印结果如下:

path:   /Users/apple/Library/Application Support/iPhone Simulator/4.3/Applications/550AF26D-174B-42E6-881B-B7499FAA32B7

看看两者打印出来的结果,我们可以看出这两种方法的不同

2.

这个主要就是返回一个绝对路径用来存放我们需要储存的文件。

  1. (NSString *)dataFilePath {
  2. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  3. NSString *documentsDirectory = [paths objectAtIndex:0];
  4. return [documentsDirectory stringByAppendingPathComponent:@"shoppingCar.plist"];
  5. }
  6. NSFileManager* fm=[NSFileManager defaultManager];
  7. if(![fm fileExistsAtPath:[self dataFilePath]]){
  8. //下面是对该文件进行制定路径的保存
  9. [fm createDirectoryAtPath:[self dataFilePath] withIntermediateDirectories:YES attributes:nil error:nil];
  10. //取得一个目录下得所有文件名
  11. NSArray *files = [fm subpathsAtPath: [self dataFilePath] ];
  12. //读取某个文件
  13. NSData *data = [fm contentsAtPath:[self dataFilePath]];
  14. //或者
  15. NSData *data = [NSData dataWithContentOfPath:[self dataFilePath]];
  16. }

3.

因为应用是在沙箱(sandbox)中的,在文件读写权限上受到限制,只能在几个目录下读写文件:

  • Documents:应用中用户数据可以放在这里,iTunes备份和恢复的时候会包括此目录
  • tmp:存放临时文件,iTunes不会备份和恢复此目录,此目录下文件可能会在应用退出后删除
  • Library/Caches:存放缓存文件,iTunes不会备份此目录,此目录下文件不会在应用退出删除

在Documents目录下创建文件

代码如下:

  1. NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory
  2. , NSUserDomainMask
  3. , YES);
  4. NSLog(@"Get document path: %@",[paths objectAtIndex:0]);
  5. NSString *fileName=[[paths objectAtIndex:0] stringByAppendingPathComponent:@"myFile"];
  6. NSString *content=@"a";
  7. NSData *contentData=[content dataUsingEncoding:NSASCIIStringEncoding];
  8. if ([contentData writeToFile:fileName atomically:YES]) {
  9. NSLog(@">>write ok.");
  10. }

可以通过ssh登录设备看到Documents目录下生成了该文件。

上述是创建ascii编码文本文件,如果要带汉字,比如:

  1. NSString *fileName=[[paths objectAtIndex:0] stringByAppendingPathComponent:@"myFile"];
  2. NSString *content=@"更深夜静人已息";
  3. NSData *contentData=[content dataUsingEncoding:NSUnicodeStringEncoding];
  4. if ([contentData writeToFile:fileName atomically:YES]) {
  5. NSLog(@">>write ok.");
  6. }

如果还用ascii编码,将不会生成文件。这里使用NSUnicodeStringEncoding就可以了。

通过filezilla下载到创建的文件打开,中文没有问题:

在其他目录下创建文件

如果要指定其他文件目录,比如Caches目录,需要更换目录工厂常量,上面代码其他的可不变:

  1. NSArray *paths=NSSearchPathForDirectoriesInDomains(NSCachesDirectory
  2. , NSUserDomainMask
  3. , YES);

使用NSSearchPathForDirectoriesInDomains只能定位Caches目录和Documents目录。

tmp目录,不能按照上面的做法获得目录了,有个函数可以获得应用的根目录:

NSHomeDirectory()

也就是Documents的上级目录,当然也是tmp目录的上级目录。那么文件路径可以这样写:

NSString *fileName=[NSHomeDirectory() stringByAppendingPathComponent:@"tmp/myFile.txt"];

或者,更直接一点,可以用这个函数:

NSTemporaryDirectory()

不过生成的路径将可能是:

…/tmp/-Tmp-/myFile.txt

使用资源文件

在编写应用项目的时候,常常会使用资源文件,比如:

安装到设备上后,是在app目录下的:

以下代码演示如何获取到文件并打印文件内容:

  1. NSString *myFilePath = [[NSBundle mainBundle]
  2. pathForResource:@"f"
  3. ofType:@"txt"];
  4. NSString *myFileContent=[NSString stringWithContentsOfFile:myFilePath encoding:NSUTF8StringEncoding error:nil];
  5. NSLog(@"bundel file path: %@ \nfile content:%@",myFilePath,myFileContent);

代码运行效果:

NSSearchPathForDirectoriesInDomains用法(转)的更多相关文章

  1. 沙盒操作的核心函数 - NSSearchPathForDirectoriesInDomains用法

    1. iPhone会为每一个应用程序生成一个私有目录,这个目录位于: /Users/sundfsun2009/Library/Application Support/iPhone Simulator/ ...

  2. NSSearchPathForDirectoriesInDomains用法

    iPhone会为每一个应用程序生成一个私有目录,这个目录位于: /Users/sundfsun2009/Library/Application Support/iPhone Simulator/Use ...

  3. (一二七)NSURLSession的基本用法 下载与数据获取

    简介 NSURLSession是苹果官方提供的一系列网络接口库,使用他们可以轻松实现下载和数据获取等任务.在上一篇文章中,我们介绍了使用NSURLConnection下载文件和断点续传的功能,实现起来 ...

  4. ios中UIWebview和asiHttprequest的用法

    原文地址为:http://www.cnblogs.com/pengyingh/articles/2343062.htmlasiHttprequest的用法 它对Get请求的响应数据进行缓存(被缓存的数 ...

  5. webview中事件的用法

    封装 MBProgressHud ==================================== #import "MBProgressHUD.h" @interface ...

  6. 李洪强iOS开发之FMDB线程安全的用法

    // //  ViewController.m //  04 - FMDB线程安全的用法 // //  Created by 李洪强 on 2017/6/6. //  Copyright © 2017 ...

  7. 李洪强iOS开发之-FMDB的用法

    // //  ViewController.m //  04 - FMDB的用法 // //  Created by 李洪强 on 2017/6/6. //  Copyright © 2017年 李洪 ...

  8. SQLite-FMDatabase用法

    FMDatabase用法 转载 http://blog.sina.com.cn/s/blog_94d94f1a01015gcr.html 以下是FMDB的一些基本使用,FMDB框架其实只是一层很薄的封 ...

  9. EditText 基本用法

    title: EditText 基本用法 tags: EditText,编辑框,输入框 --- EditText介绍: EditText 在开发中也是经常用到的控件,也是一个比较必要的组件,可以说它是 ...

随机推荐

  1. CSAPP学习笔记 第一章 计算机系统漫游

    Ch 1.0 1.计算机系统是由硬件和系统软件组成的 2.本书阐述了计算机组件是如何工作的以及执行组件是如何影响程序正确性和性能的. 3.通过跟踪hello程序的生命周期来开始对系统的学习. #inc ...

  2. ZOJ 1456 Minimum Transport Cost(floyd+后继路径记录)

    http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1456 题意:求最短路并且输出字典序最小的答案. 思路:如果用dijkstr ...

  3. vue-echarts的使用及编译报错解决方法

    一. 使用 vue-cli 快速构建vue项目, 引入vue-echarts组件 安装:  > npm i vue-echarts --save 修改 webpack.config.js 配置: ...

  4. Codeforces Round #406 (Div. 2) D. Legacy 线段树建模+最短路

    D. Legacy time limit per test 2 seconds memory limit per test 256 megabytes input standard input out ...

  5. c++ 查找容器中不满足条件的元素,返回iterator(find_if_not)

    #include <iostream> // std::cout #include <algorithm> // std::find_if_not #include <a ...

  6. Jmeter 中对响应报文处理后断言用到BeanShell Assertion

    Jmeter中常用的断言可以是Response Assertion 如果需要对响应报文中的某个字符串进行解码,对解码之后的值在进行断言要怎么做呢? 仔细观察一下,可以用下面俩个元件 Regular E ...

  7. C++学习笔记(二)——交换函数(swap)

    这次我们要透过一个简单的函数swap深入理解函数传参的本质以及在C++中如何选择传参方式. 先来看第一段程序: void swap(int x, int y) { int temp = y; y = ...

  8. springboot集成mybatis及mybatis generator工具使用

    原文链接 前言mybatis是一个半自动化的orm框架,所谓半自动化就是mybaitis只支持数据库查出的数据映射到pojo类上,而实体到数据库的映射需要自己编写sql语句实现,相较于hibernat ...

  9. Phalcon框架数据库读写分离的实现方法

    Phalcon框架和Yaf类似,是一款用C实现的拓展级别的框架,不过其功能实现更加丰富,设计思路基于依赖注入.容器等方式,更符合现代框架思想.本文主要针对Phalcon框架数据库层的读写分离进行说明, ...

  10. ajax post data 获取不到数据,注意contentType

    $.ajax({ url:'/web/register/', type:"POST", data:{'user':'66'}, dataType:'json', 这个东西困惑我一天 ...