IOS开发 沙盒中的文件操作

1、获取程序的Home目录

NSString*path = NSHomeDirectory();

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

打印结果:

2012-07-11 11:18:16.291 TestProject[2387:f803] path:/Users/username/Library/Application Support/iPhone Simulator/5.1/Applications/BAE91297-A4C6-4DDC-A9DA-7B790B36CE7A

真机上的目录是:

2012-06-17 14:25:47.059 IosSandbox[4281:f803]/var/mobile/Applications/3B8EC78A-5EEE-4C2F-B0CB-4C3F02B996D2

可见,真机上的目录是/var/mobile/Applications/这个目录下的,和模拟器不一样。这个是Home目录,其他的子目录和模拟器一样。

2、获取Document目录

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

NSString*path=[pathsobjectAtIndex:0];

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

打印结果:

2012-07-11 11:21:22.879 TestProject[2417:f803] path:/Users/username/Library/Application Support/iPhone Simulator/5.1/Applications/BAE91297-A4C6-4DDC-A9DA-7B790B36CE7A/Documents

3、获取Cache目录

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

NSString*path=[pathsobjectAtIndex:0];

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

打印结果:

2012-07-11 11:13:36.162 TestProject[2310:f803] path:/Users/username/Library/Application Support/iPhone Simulator/5.1/Applications/BAE91297-A4C6-4DDC-A9DA-7B790B36CE7A/Library/Caches

4、获取Library目录

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

NSString*path=[pathsobjectAtIndex:0];

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

打印结果:

2012-07-11 11:14:41.138 TestProject[2337:f803] path:/Users/username/Library/Application Support/iPhone Simulator/5.1/Applications/BAE91297-A4C6-4DDC-A9DA-7B790B36CE7A/Library

5、获取Tmp目录

NSString*path=NSTemporaryDirectory();

NSLog(@"%@", path);

打印结果:

2012-07-11 11:16:09.438 TestProject[2358:f803] path:/var/folders/hj/8sgyk0f555l1z_n95p2b2kp00000gn/T/

6、写入文件

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

NSString *docDir = [paths objectAtIndex:0];

if(!docDir) {

NSLog(@"Documents 目录未找到");

}

NSArray *array = [[NSArray alloc]initWithObjects:@"内容",@"content",nil];

NSString *filePath = [docDir stringByAppendingPathComponent:@"testFile.txt"];

[array writeToFile:filePath atomically:YES];

7、读取文件

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

NSString *docDir = [paths objectAtIndex:0];

NSString *filePath = [docDir stringByAppendingPathComponent:@"testFile.txt"];

NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];

NSLog(@"%@",array);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 每个iOS应用都有自己的应用沙盒(应用沙盒就是文件系统目录),与其他文件系统隔离。应用必须待在自己的沙盒里,其他应...
    凸阿滨阅读 424评论 0 0
  • 今天就本周作业的读取txt文件查找了的一些方法,如下: //读取文本内容NSError *error;NSStri...
    霏誠拜咬o阅读 632评论 0 0
  • 提到数据持久化 我们必须得先了解IOS程序的沙盒机制(sandBox)。 1.IOS沙盒机制介绍 iOS应用程...
    _Half______阅读 12,583评论 4 24
  • iOS沙盒机制 沙盒机制 不好意思,我又一次来到了你们的世界,其实我是拒绝的,但是我的无法忍受内心的躁动!额我TM...
    iOSDevVicky阅读 2,003评论 0 12
  • 正则登陆验证 *accont—->手机号 以1开头,10位结尾。哈哈,还有其他各种写法,我这里使用了简单的。 *p...
    诗和远方together阅读 2,173评论 0 0