IOS开发-UI学习-沙盒机制&文件操作

ž苹果为软件的运行提供了一个沙盒机制
每个沙盒含有3个文件夹:Documents, Library 和 tmp。因为应用的沙盒机制,应用只能在几个目录下读写文件
žDocuments:苹果建议将程序中建立的或在程序中浏览到的文件数据保存在该目录下,iTunes备份和恢复的时候会包括此目录
žLibrary:存储程序的默认设置或其它状态信息;
žLibrary/Caches:存放缓存文件,iTunes不会备份此目录,此目录下文件不会在应用退出删除;
žtmp:提供一个即时创建临时文件的地方,
 
这三个文件夹如图:
 
 
 
对于Documents和Library可以有几种方式去获得它的路径,而tmp只有一种方式。这些获取路径的方式大多是C语言中的文件操作函数。
 
 1 //    获得并打印本app的沙盒,里面有三个文件夹,doucment,library,tmp
 2     NSString * homepath = [NSString stringWithFormat:@"%@",NSHomeDirectory()];
 3     NSLog(@"%@",homepath);
 4     
 5     
 6 //    获得并打印document路径的第一种方法
 7     NSString *documentPath = [NSString stringWithFormat:@"%@/Documents",NSHomeDirectory()];
 8     NSLog(@"%@",documentPath);
 9     
10     
11 //    获得并打印document路径的第二种方法,拿到的是一个数组,而document路径是这个数组的第一个元素。
12     NSArray *documentPath2 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
13     NSLog(@"%@",[documentPath2 objectAtIndex:0]);
14     
15     
16     
17 //    获得并打印caches路径的方法1:
18     NSArray *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
19     NSLog(@"%@",cachePath[0]);
20     
21     
22 //    获得并打印cache路径的方法2:
23     NSString *cachePath2 = [NSString stringWithFormat:@"%@/Library/Caches",NSHomeDirectory()];
24     NSLog(@"%@",cachePath2);
25     
26     
27 //    获取并打印tmp路径的方法
28     NSString *tmpPath = NSTemporaryDirectory();
29     NSLog(@"%@",tmpPath);

 

 
在程序文件夹中创建一个新的文件夹的操作;
1 //    在document下面创建一个文件夹
2 //    先创建一个路径
3     NSString *newPath = [NSString stringWithFormat:@"%@/Documents/New",NSHomeDirectory()];
4     NSLog(@"%@",newPath);
5 //    再使用之前创建的路径使用NsFileManager去创建一个文件夹,yesOrNo返回是否创建成功的消息
6     BOOL yesOrNo = [[NSFileManager defaultManager]createDirectoryAtPath:newPath withIntermediateDirectories:YES attributes:nil error:nil];

新建完成后在Documents下面多了一个文件夹New。

 

 

创建文件new.mp3:

1 //    创建文件
2 //    先把文件路径和文件名定义好
3     NSString *newfile = [NSString stringWithFormat:@"%@/new.mp3",newPath];
4 //    使用createFileAtPath创建文件
5     [[NSFileManager defaultManager]createFileAtPath:newfile contents:nil attributes:nil];

 

 

删除文件new.mp3

1 //    删除文件
2     [[NSFileManager defaultManager]removeItemAtPath:newfile error:nil];
3     

 

 

posted @ 2016-03-30 11:41  jiwangbujiu  阅读(547)  评论(0编辑  收藏  举报