IOS获得各种文档文件夹路径的方法

iphone沙箱模型的有四个目录,各自是什么,永久数据存储一般放在什么位置。得到模拟器的路径的简单方式是什么.

documents,tmp。app,Library。

(NSHomeDirectory())。

手动保存的文件在documents文件中

Nsuserdefaults保存的文件在tmp目录里


1、Documents 文件夹:您应该将全部de应用程序数据文件写入到这个文件夹下。

这个文件夹用于存储用户数据或其他应该定期备份息。

2、AppName.app 文件夹:这是应用程序程序包文件夹。包括应用程序身。因为应用程序必须经过签名,所以您在执行时不能对这个文件夹中内容进行改动。否则可能会使应用程序无法启动。

3、Library 文件夹:这个文件夹下有两个子文件夹:Caches 和 Preferences
Preferences 文件夹:包括应用程序偏好设置文件。

您不应该直接创建偏好设置文件,而是应该使用NSUserDefaults类来取得和设置应用程序偏好.
Caches 文件夹:用于存放应用程序专用支持文件,保存应用程序再次启动过程中须要信息。

4、tmp 文件夹:这个文件夹用于存放暂时文件,保存应用程序再次启动过程中不须要信息。


获取这些文件夹路径方法:
1,获取家文件夹路径函数:
NSString *homeDir = NSHomeDirectory();
2,获取Documents文件夹路径方法:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
3,获取Caches文件夹路径方法:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [paths objectAtIndex:0];
4,获取tmp文件夹路径方法:
NSString *tmpDir = NSTemporaryDirectory();
5,获取应用程序程序包中资源文件路径方法:
比如获取程序包中一个图片资源(apple.png)路径方法:
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@”apple” ofType:@”png”];
UIImage *appleImage = [[UIImage alloc] initWithContentsOfFile:imagePath];
代码中mainBundle类方法用于返回一个代表应用程序包对象。

iphone沙盒(sandbox)中的几个文件夹获取方式:
  1. // 获取沙盒主文件夹路径  
  2. NSString *homeDir = NSHomeDirectory();  
  3. // 获取Documents文件夹路径  
  4. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
  5. NSString *docDir = [paths objectAtIndex:0];  
  6. // 获取Caches文件夹路径  
  7. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);  
  8. NSString *cachesDir = [paths objectAtIndex:0];  
  9. // 获取tmp文件夹路径  
  10. NSString *tmpDir =  NSTemporaryDirectory();  
  1. // 获取当前程序包中一个图片资源(apple.png)路径  
  2. NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"apple" ofType:@"png"];  
  3. UIImage *appleImage = [[UIImage alloc] initWithContentsOfFile:imagePath];  

样例:

NSFileManager* fm=[NSFileManager defaultManager];
if(![fm fileExistsAtPath:[self dataFilePath]]){

//以下是对该文件进行制定路径保存
[fm createDirectoryAtPath:[self dataFilePath] withIntermediateDirectories:YES attributes:nil error:nil];

//取得一个文件夹下得全部文件名称
NSArray *files = [fm subpathsAtPath: [self dataFilePath] ];

//读取某个文件
NSData *data = [fm contentsAtPath:[self dataFilePath]];

//或者
NSData *data = [NSData dataWithContentOfPath:[self dataFilePath]];
}

版权声明:本文博客原创文章,博客,未经同意,不得转载。

原文地址:https://www.cnblogs.com/yxwkf/p/4716963.html