美文网首页iOS 开发 iOS Developer
想了解沙盒?看我就够了!

想了解沙盒?看我就够了!

作者: rogertan30 | 来源:发表于2016-04-11 17:01 被阅读804次

    iOS应用程序只能在为该改程序创建的文件系统中读取文件,不可以去其它地方访问,此区域被成为沙盒,所以所有的非代码文件都要保存在此,例如图像,图标,声音,映像,属性列表,文本文件等。

    沙盒文件的目录结构:

    • Documents

    • Library

      • Caches

      • Preferences

    • tmp

    沙盒下各文件夹保存内容的区别

    • Documents:保存应用运行时生成的需要持久化的数据,iTunes同步设备时会备份该目录。例如,游戏应用可以将游戏存档保存在该目录下。如果用户将缓存存放在这个文件夹下,会导致应用审核无法通过。
    • tmp:保存应用运行时所需要的临时数据,使用完毕后再将相应的文件从该目录删除。应用没有运行时,系统也可能会清除该目录下的文件。iTunes同步设备时不会备份该目录。
    • Library/Caches:保存应用运行时生成的需要持久化的数据,iTunes同步设备时不会备份该目录。一般存储体积大,不需要备份的非重要数据。
    • Library/Preference:保存应用的所有偏好设置,iOS的Settings(设置)应用会在该目录中查找应用的设置信息。iTunes同步设备时会备份该目录。

    获取程序的Home目录

    NSString *homeDirectory = NSHomeDirectory();
    NSLog(@"path:%@", homeDirectory);
    

    获取document目录

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    

    获取Cache目录

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    

    获取Library目录

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    

    获取Tmp目录

    NSString *tmpDir = NSTemporaryDirectory();
    NSLog(@"%@", tmpDir);
    

    创建文件夹

    -(void)createDirectory{
        NSString *documentsPath =[self getDocumentsPath];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *iOSDirectory = [documentsPath stringByAppendingPathComponent:@"/iOS"];
        BOOL isSuccess = [fileManager createDirectoryAtPath:iOSDirectory withIntermediateDirectories:YES attributes:nil error:nil];
        if (isSuccess) {
            NSLog(@"success");
        } else {
            NSLog(@"fail");
        }
    }
    

    创建文件

    -(void)createFile{
        NSString *documentsPath =[self getDocumentsPath];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *iOSPath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
        BOOL isSuccess = [fileManager createFileAtPath:iOSPath contents:nil attributes:nil];
        if (isSuccess) {
            NSLog(@"success");
        } else {
            NSLog(@"fail");
        }
    }
    

    写文件

    -(void)writeFile{
        NSString *documentsPath =[self getDocumentsPath];
        NSString *iOSPath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
        NSString *content = @"我要写数据啦";
        BOOL isSuccess = [content writeToFile:iOSPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
        if (isSuccess) {
            NSLog(@"write success");
        } else {
            NSLog(@"write fail");
        }
    }
    
    NSString * fileName = @"testFileNSFileManager.txt";
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    //获取文件路径
    NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
    //待写入的数据
    NSString *temp = @"nihao 世界";
    int dataInt = 1234;
    float dataFloat = 3.14f;
    //创建数据缓冲
    NSMutableData *writer = [[NSMutableData alloc] init];
    //将字符串添加到缓冲中
    [writer appendData:[temp dataUsingEncoding:NSUTF8StringEncoding]];
    //将其他数据添加到缓冲中
    [writer appendBytes:&dataInt length:sizeof(dataInt)];
    [writer appendBytes:&dataFloat length:sizeof(dataFloat)];
    //将缓冲的数据写入到文件中
    [writer writeToFile:path atomically:YES];
    

    读取文件内容

    -(void)readFileContent{
        NSString *documentsPath =[self getDocumentsPath];
        NSString *iOSPath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
        NSString *content = [NSString stringWithContentsOfFile:iOSPath encoding:NSUTF8StringEncoding error:nil];
        NSLog(@"read success: %@",content);
    }
    
    //读取数据:
    int intData;
    float floatData = 0.0;
    NSString *stringData;
    
    NSData *reader = [NSData dataWithContentsOfFile:path];
    stringData = [[NSString alloc] initWithData:[reader subdataWithRange:NSMakeRange(0, [temp length])]
                                       encoding:NSUTF8StringEncoding];
    [reader getBytes:&intData range:NSMakeRange([temp length], sizeof(intData))];
    [reader getBytes:&floatData range:NSMakeRange([temp length] + sizeof(intData), sizeof(floatData))];
    NSLog(@"stringData:%@ intData:%d floatData:%f", stringData, intData, floatData);
    

    判断文件是否存在

    - (BOOL)isSxistAtPath:(NSString *)filePath{
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL isExist = [fileManager fileExistsAtPath:filePath];
        return isExist;
    }
    

    计算文件大小

    - (unsigned long long)fileSizeAtPath:(NSString *)filePath{
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL isExist = [fileManager fileExistsAtPath:filePath];
        if (isExist){
            unsigned long long fileSize = [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
            return fileSize;
        } else {
            NSLog(@"file is not exist");
            return 0;
        }
    }
    

    计算整个文件夹中所有文件大小

    - (unsigned long long)folderSizeAtPath:(NSString*)folderPath{
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL isExist = [fileManager fileExistsAtPath:folderPath];
        if (isExist){
            NSEnumerator *childFileEnumerator = [[fileManager subpathsAtPath:folderPath] objectEnumerator];
            unsigned long long folderSize = 0;
            NSString *fileName = @"";
            while ((fileName = [childFileEnumerator nextObject]) != nil){
                NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
                folderSize += [self fileSizeAtPath:fileAbsolutePath];
            }
            return folderSize / (1024.0 * 1024.0);
        } else {
            NSLog(@"file is not exist");
            return 0;
        }
    }
    

    删除文件

    -(void)deleteFile{
        NSString *documentsPath =[self getDocumentsPath];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *iOSPath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
        BOOL isSuccess = [fileManager removeItemAtPath:iOSPath error:nil];
        if (isSuccess) {
            NSLog(@"delete success");
        }else{
            NSLog(@"delete fail");
        }
    }
    

    移动文件

    - (void)moveFileName
    {
        NSString *documentsPath =[self getDocumentsPath];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *filePath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
        NSString *moveToPath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
        BOOL isSuccess = [fileManager moveItemAtPath:filePath toPath:moveToPath error:nil];
        if (isSuccess) {
            NSLog(@"rename success");
        }else{
            NSLog(@"rename fail");
        }
    }
    

    重命名

    - (void)renameFileName
    {
        //通过移动该文件对文件重命名
        NSString *documentsPath =[self getDocumentsPath];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *filePath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
        NSString *moveToPath = [documentsPath stringByAppendingPathComponent:@"rename.txt"];
        BOOL isSuccess = [fileManager moveItemAtPath:filePath toPath:moveToPath error:nil];
        if (isSuccess) {
            NSLog(@"rename success");
        }else{
            NSLog(@"rename fail");
        }
    }
    

    相关文章

      网友评论

        本文标题:想了解沙盒?看我就够了!

        本文链接:https://www.haomeiwen.com/subject/ihyilttx.html