IOS沙盒机制

iOS应用数据常见的存储方式:

1、XML属性列表(plist)归档

2、Preference(偏好设置)

3、NSKeyedArchiver归档(NSCoding)

4、SQLite3

5、CoreData

出于安全考虑,iPhone对于安装在上面的应用程序有所限制,这个限制就是应用程序只能在为该改程序创建的文件系统中读取文件,不可以去其它地方访问,此区域被成为沙盒,所以所有的非代码文件都要保存在此,例如图像,图标,声音,映像,属性列表,文本文件等。总体来说沙盒就是一种独立、安全、封闭的空间。 ##沙盒机制的特点

  • 每个应用程序都有自己的存储空间。
  • 每个应用程序都不可以翻过自己的围墙去访问别的存储空间的内容。(已经越狱的除外)
  • 在访问别人沙盒内的数据时需要访问权限。

应用程序沙盒目录下有三个文件夹Documents、Library(下面有Caches和Preferences目录)、tmp。

  • Documents:保存应用运行时生成的需要持久化的数据iTunes会自动备份该目录。苹果建议将在应用程序中浏览到的文件数据保存在该目录下。
  • Library/Caches:一般存储的是缓存文件,例如图片视频等,此目录下的文件不会再应用程序退出时删除,在手机备份的时候,iTunes不会备份该目录。
  • Library/Preferences:保存应用程序的所有偏好设置iOS的Settings(设置),我们不应该直接在这里创建文件,而是需要通过NSUserDefault这个类来访问应用程序的偏好设置。iTunes会自动备份该文件目录下的内容。
  • tmp:临时文件目录,在程序重新运行的时候,和开机的时候,会清空tmp文件夹

 

 

  • 获取Documents文件路径
  • /**
         *      获取Document下的文件路径
         *
         *      @param NSDocumentDirectory 获取Document目录
         *      @param NSUserDomainMask    是在当前沙盒范围内查找
         *      @param YES                 展开路径,NO是不展开
         *
         *      @return test.txt文件的路径
         */
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
    NSUserDomainMask, YES)firstObject]stringByAppendingPathComponent:@"test.txt"];
  • 获取Library文件路径
  • /**
         *      获取Library目录下文件路径
         *
         *      @param NSLibraryDirectory 获取Library目录
         *      @param NSUserDomainMask   在当前的沙盒范围内查找
         *      @param YES                展开路径,NO不展开路径
         *
         *      @return test.txt文件的路径
         */
        NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, 
    NSUserDomainMask, YES)firstObject]stringByAppendingPathComponent:@"test.txt"];
  • 获取Library/Caches文件目录
  • /**
         *      获取Library目录下文件路径
         *
         *      @param NSCachesDirectory 获取Library/Caches目录
         *      @param NSUserDomainMask  在当前的沙盒范围内查找
         *      @param YES               展开路径,NO不展开路径
         *
         *      @return test.txt文件的路径
         */
        NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, 
    NSUserDomainMask, YES)firstObject]stringByAppendingPathComponent:@"test.txt"];
  • 获取Library/Preferences,Preferences由系统维护,不需要我们手动的获取文件路径进行操作,而是需要借助NSUserDefault来操作,但是我们是可以获取到这个文件的。
  • /**
         *      获取Library目录下文件路径
         *
         *      @param NSLibraryDirectory 获取Library目录
         *      @param NSUserDomainMask   在当前的沙盒范围内查找
         *      @param YES                展开路径,NO不展开路径
         *
         *      @return Preferences文件的路径
         */
    
        NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, 
    NSUserDomainMask, YES)firstObject]stringByAppendingPathComponent:@"Preferences"];
  • 获取tmp文件路径
  •  /**
         *      获取tmp文件目录下的文件路径
         *
         *      @return test.txt的文件路径
         */
        NSString *filePath = [NSTemporaryDirectory()stringByAppendingPathComponent:@"test.txt"];

     

  • 创建文件夹
  • +(BOOL)creatDir:(NSString *)path{
        if (path.length==0) {
            return NO;
        }
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL isSuccess = YES;
        BOOL isExist = [fileManager fileExistsAtPath:path];
        if (isExist==NO) {
            NSError *error;
            if (![fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error]) {
                isSuccess = NO;
                NSLog(@"creat Directory Failed:%@",[error localizedDescription]);
            }
        }
        return isSuccess;
    }
  • 创建文件
  • +(BOOL)creatFile:(NSString*)filePath{
        if (filePath.length==0) {
            return NO;
        }
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:filePath]) {
            return YES;
        }
        NSError *error;
        NSString *dirPath = [filePath stringByDeletingLastPathComponent];
        BOOL isSuccess = [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:&error];
        if (error) {
            NSLog(@"creat File Failed:%@",[error localizedDescription]);
        }
        if (!isSuccess) {
            return isSuccess;
        }
        isSuccess = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
        return isSuccess;
    }
  • 写数据
  • +(BOOL)writeToFile:(NSString*)filePath contents:(NSData *)data{
        if (filePath.length==0) {
            return NO;
        }
        BOOL result = [self creatFile:filePath];
        if (result) {
            if ([data writeToFile:filePath atomically:YES]) {
                NSLog(@"write Success");
            }else{
                NSLog(@"write Failed");
            }
        }
        else{
            NSLog(@"write Failed");
        }
        return result;
    }
  • 追加写数据
  • +(BOOL)appendData:(NSData*)data withPath:(NSString *)filePath{
        if (filePath.length==0) {
            return NO;
        }
        BOOL result = [self creatFile:filePath];
        if (result) {
            NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:filePath];
            [handle seekToEndOfFile];
            [handle writeData:data];
            [handle synchronizeFile];
            [handle closeFile];
        }
        else{
            NSLog(@"appendData Failed");
        }
        return result;
    }
  • 读文件数据
  • +(NSData*)readFileData:(NSString *)path{
        NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
        NSData *fileData = [handle readDataToEndOfFile];
        [handle closeFile];
        return fileData;
    }
  • 获取文件夹下所有的文件列表
  • +(NSArray*)getFileList:(NSString*)path{
        if (path.length==0) {
            return nil;
        }
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSError *error;
        NSArray *fileList = [fileManager contentsOfDirectoryAtPath:path error:&error];
        if (error) {
            NSLog(@"getFileList Failed:%@",[error localizedDescription]);
        }
        return fileList;
    }
  • 获取文件夹下所有文件(深度遍历)
  • +(NSArray*)getAllFileList:(NSString*)path{
        if (path.length==0) {
            return nil;
        }
        NSArray *fileArray = [self getFileList:path];
        NSMutableArray *fileArrayNew = [NSMutableArray array];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        for (NSString *aPath in fileArray) {
            NSString * fullPath = [path stringByAppendingPathComponent:aPath];
            BOOL isDir = NO;
            if ([fileManager fileExistsAtPath:fullPath isDirectory:&isDir]) {
                if (isDir) {
                    [fileArrayNew addObjectsFromArray:[self getAllFileList:fullPath]];
                }else{
                    [fileArrayNew addObject:fullPath];
                }
            }
        }
        return fileArrayNew;
    }
  • 移动文件
  • +(BOOL)moveFile:(NSString *)fromPath toPath:(NSString *)toPath toPathIsDir:(BOOL)dir{
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if (![fileManager fileExistsAtPath:fromPath]) {
            NSLog(@"Error: fromPath Not Exist");
            return NO;
        }
        BOOL isDir = NO;
        BOOL isExist = [fileManager fileExistsAtPath:toPath isDirectory:&isDir];
        if (isExist) {
            if (isDir) {
                if ([self creatDir:toPath]) {
                    NSString *fileName = fromPath.lastPathComponent;
                    toPath = [toPath stringByAppendingPathComponent:fileName];
                    return [self moveItemAtPath:fromPath toPath:toPath];
                }
            }else{
                [self removeFile:toPath];
                return [self moveItemAtPath:fromPath toPath:toPath];
            }
        }
        else{
            if (dir) {
                if ([self creatDir:toPath]) {
                    NSString *fileName = fromPath.lastPathComponent;
                    toPath = [toPath stringByAppendingPathComponent:fileName];
                    return [self moveItemAtPath:fromPath toPath:toPath];
                }
            }else{
                return [self moveItemAtPath:fromPath toPath:toPath];
            }
        }
        return NO;
    }
    +(BOOL)moveItemAtPath:(NSString*)fromPath toPath:(NSString*)toPath{
        BOOL result = NO;
        NSError * error = nil;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        result = [fileManager moveItemAtPath:fromPath toPath:toPath error:&error];
        if (error){
            NSLog(@"moveFile Fileid:%@",[error localizedDescription]);
        }
        return result;
    }
  • 删除文件
  • +(BOOL)removeFile:(NSString*)filePath{
        BOOL isSuccess = NO;
        NSError *error;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        isSuccess = [fileManager removeItemAtPath:filePath error:&error];
        if (error) {
            NSLog(@"removeFile Field:%@",[error localizedDescription]);
        }else{
            NSLog(@"removeFile Success");
        }
        return isSuccess;
    }
  • 删除文件夹
  • +(BOOL)removeDir:(NSString*)path{
        return [self removeFile:path];
    }
  • 删除某些后缀的文件
  • +(void)removeFileSuffixList:(NSArray<NSString*>*)suffixList filePath:(NSString*)path deep:(BOOL)deep{
        NSArray *fileArray = nil;
        if (deep) {  // 是否深度遍历
            fileArray = [self getAllFileList:path];
        }else{
            fileArray = [self getFileList:path];
            NSMutableArray *fileArrayTmp = [NSMutableArray array];
            for (NSString *fileName in fileArray) {
                NSString* allPath = [path stringByAppendingPathComponent:fileName];
                [fileArrayTmp addObject:allPath];
            }
            fileArray = fileArrayTmp;
        }
        for (NSString *aPath in fileArray) {
            for (NSString* suffix in suffixList) {
                if ([aPath hasSuffix:suffix]) {
                    [self removeFile:aPath];
                }
            }
        }
    }
  • 获取文件大小
  • +(long long)getFileSize:(NSString*)path{
        unsigned long long fileLength = 0;
        NSNumber *fileSize;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:nil];
        if ((fileSize = [fileAttributes objectForKey:NSFileSize])) {
            fileLength = [fileSize unsignedLongLongValue]; //单位是 B
        }
        return fileLength;
    }
  • 获取文件的信息(包含了上面文件大小)
  • +(NSDictionary*)getFileInfo:(NSString*)path{
        NSError *error;
        NSDictionary *reslut =  [[NSFileManager defaultManager] attributesOfItemAtPath:path error:&error];
        if (error) {
            NSLog(@"getFileInfo Failed:%@",[error localizedDescription]);
        }
        return reslut;
    }

     

posted @ 2019-07-03 17:04  时光清浅、  阅读(331)  评论(0编辑  收藏  举报