iOS沙盒存储的基本使用

简介

iOS 应用程序在安装时,会创建属于自己的沙盒文件(standbox)。应用程序中所有的非代码文件都保存在沙盒中,如图片、声音、属性列表,sqlite数据库和文本文件等。
在沙盒机制下,每个应用程序之间的文件夹不能互相访问。iOS系统为了保证系统安全,采用了这种机制。
其原理是通过重定向技术,把应用程序生成和修改的文件,定向到自身文件夹中。

沙盒目录组成

沙盒的的根目录有三个文件夹:Documents,Library,tmp


image.png

image.png

子目录有Caches、Preferences等文件夹,其中 Documents 和 Preferences 会被 iCloud 同步。

值得注意的是,NSUserDefaults是存储在 Preferences 下的文件,发现有很多开发者为了偷懒,频繁的使用NSUserDefaults做任意数据的磁盘缓存。
这是一个很不合理的做法,用处不大。且大量的数据一般缓存在 Caches 中。就算是从技术角度考虑,NSUserDefaults是以 .plist 形式存储的,不适合大数据存储。

查找文件路径

NSSearchPathForDirectoriesInDomains()是用来查找文件路径的函数。

返回值:是一个数组,其中只有一个NSString元素,即查找的路径。
参数1:NSDocumentDirectory表示需要查找的目录
参数2:NSUserDomainMask表示在用户的主目录中查找
参数3:YES表示返回路径展开

  • 沙盒根目录的路径
    通过NSHomeDirectory()获取沙盒路径。
NSString *path = NSHomeDirectory();
NSLog(@"%@", path);
  • 获取Documents目录的路径
    参数1是NSDocumentDirectory
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;

  • 获取Library目录的路径
    参数1是NSLibraryDirectory
NSString *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;

  • 获取Caches目录的路径
    参数1是NSCachesDirectory
 NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;

此目录用来保存应用程序运行时,生成的需要持久化的数据,这些数据一般存储体积较大,又不十分重要,如网络请求数据等。需要用户负责删除。

  • 获取Preferences目录的路径
NSString *path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"Preferences"];

此目录保存应用程序的所有偏好设置,iOS的Settings(设置)应用会在该目录中查找应用的设置信息。

  • 获取tmp文件路径
NSString *path = NSTemporaryDirectory();

此目录保存应用程序运行时,所需的临时数据,使用完毕后再将相应的文件从该目录删除。应用没有运行时,系统也可能会清除该目录下的文件。

保存图片到沙盒

    UIImage *currentImage  = photos[i];
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
   // 获取沙盒路径
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%zd.png",i]];
    // 写入
    [imageData writeToFile:fullPath atomically:YES];   

从沙盒读取图片

// 读取图片
NSString * fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Docments"] stringByAppendingPathComponent:@"currentImage.png"];
UIImage * savedImage = [[UIImage alloc] initWithContentsOfFile:fullPath];

删除沙盒文件

-(void)deleteFile {
    NSFileManager * fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    
    //文件名
    NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:@"pin.png"];
    BOOL isExit =[[NSFileManager defaultManager] fileExistsAtPath:uniquePath];
    if (! isExit) {
        NSLog(@"not exit !");
        return ;
    }else {
        BOOL isDele= [fileManager removeItemAtPath:uniquePath error:nil];
        if (isDele) 
            NSLog(@"delete success");
    }
}

得到沙盒中的所有文件

    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSString *document=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *folder =[document stringByAppendingPathComponent:@"folder"];
    NSArray *fileList ;
    fileList =[fileManager contentsOfDirectoryAtPath:folder error:NULL];
    
    for (NSString *file in fileList) {
        NSLog(@"file=%@",file);
        NSString *path =[folder stringByAppendingPathComponent:file];
        NSLog(@"得到的路径=%@",path);
    }

计算文件大小

- (long long)fileSizeAtPath:(NSString *)path
{
    NSFileManager *fileManager = [NSFileManager defaultManager];

    if ([fileManager fileExistsAtPath:path])
    {
        long long size = [fileManager attributesOfItemAtPath:path error:nil].fileSize;
        return size;
    }

    return 0;
}

文件夹大小

- (long long)folderSizeAtPath:(NSString *)path
{
    NSFileManager *fileManager = [NSFileManager defaultManager];

    long long folderSize = 0;

    if ([fileManager fileExistsAtPath:path])
    {
        NSArray *childerFiles = [fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles)
        {
            NSString *fileAbsolutePath = [path stringByAppendingPathComponent:fileName];
            if ([fileManager fileExistsAtPath:fileAbsolutePath])
            {
                long long size = [fileManager attributesOfItemAtPath:fileAbsolutePath error:nil].fileSize;
                folderSize += size;
            }
        }
    }

    return folderSize;
}

相关资料

//www.greatytc.com/p/0913b8b6c858
//www.greatytc.com/p/0dbe875d7723
//www.greatytc.com/p/dd3f120eb249

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

推荐阅读更多精彩内容