西贝了爷  

默认情况下,每个沙盒必含有3个文件夹:Documents, Library 和 tmp

一、沙盒(sandbox)
出于安全的目的,应用程序只能将自己的数据和偏好设置写入到几个特定的位置上。当应用程序被安装到设备上时,系统会为其创建一个家目录,这个家目录就是应用程序的沙盒。
家目录下共有四个子目录:

  1-Documents 目录:您应该将所有的应用程序数据文件写入到这个目录下。这个目录用于存储用户数据或其它应该定期备份的信息。
  2-AppName.app 目录:这是应用程序的程序包目录,包含应用程序的本身。由于应用程序必须经过签名,所以您在运行时不能对这个目录中的内容进行修改,否则可能会使应用程序无法启动。
  3-Library 目录:这个目录下有两个子目录:Caches 和 Preferences
        Preferences 目录包含应用程序的偏好设置文件。您不应该直接创建偏好设置文件,而是应该使用NSUserDefaults类来取得和设置应用程序的偏好
        Caches 目录用于存放应用程序专用的支持文件,保存应用程序再次启动过程中需要的信息。
  4-tmp 目录:这个目录用于存放临时文件,保存应用程序再次启动过程中不需要的信息。

获取这些目录路径的方法:
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
    
    
    //取得Documents中某个文件的路径
    NSString *path = [[self documentFolder] stringByAppendingPathComponent:@"image.png"];
    
    //获取tmp目录
    NSString *tempPath = NSTemporaryDirectory();
    
    //1,获取家目录路径的函数:
    NSString *homeDir = NSHomeDirectory();
    
    //2,获取Documents目录路径/Caches目录路径的方法:
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *docDir = [paths objectAtIndex:0];
    
    
    //3,获取tmp目录路径的方法:
    NSString *tmpDir = NSTemporaryDirectory();
    
    
    
    //4,获取应用程序程序包中资源文件路径的方法:
    
    //例如获取程序包中一个图片资源(apple.png)路径的方法:
    
    NSString *imagePath = [[NSBundle mainBundle]pathForResource:@"apple"ofType:@"png"];
    
    UIImage *appleImage = [[UIImage alloc]initWithContentsOfFile:imagePath];
    
    //代码中的mainBundle类方法用于返回一个代表应用程序包的对象。
}

//取得Documents路径的方法:
- (NSString *)documentFolder {
    return [NSHomeDirectory()stringByAppendingPathComponent:@"Documents"];
}

//补充:取得应用程序包(即bundle)的路径
- (NSString *)bundleFolder {
    return [[NSBundle mainBundle]bundlePath];
}

 




二、文件IO

1,将数据写到Documents目录:

 

- (BOOL)writeApplicationData:(NSData*)data toFile:(NSString*)fileName {
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    
    NSString *docDir = [paths objectAtIndex:0];
    
    if(!docDir) {
        
        NSLog(@"Documents directory not found!");
        
        return NO;
        
    }
    
    NSString *filePath = [docDir stringByAppendingPathComponent:fileName];
    
    return [data writeToFile:filePath atomically:YES];
    
}

2,从Documents目录读取数据:
- (NSData *)applicationDataFromFile:(NSString *)fileName {

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

    NSString *docDir = [paths objectAtIndex:0];

    NSString *filePath = [docDir stringByAppendingPathComponent:fileName];

    NSData *data = [[[NSData alloc]initWithContentsOfFile:filePath]autorelease];

    return data;

}

 

 

 
posted on 2016-08-10 15:38  西贝了爷  阅读(1514)  评论(0编辑  收藏  举报