沙盒

作者: 有一种再见叫青春 | 来源:发表于2016-11-04 15:20 被阅读8次

    ios程序为沙盒机制,App只能访问自己目录下的文件,不能直接访问其他目录内容,每个APP默认都会创建以下目录结构Doucments Library tmp

    <li>Documents:存放应用程序产生的数据,会被iturns备份同步</li>
    <li>Library:包含二个子目录:Cache 和 Preferences</li>
    <ol> Preferences: 包含应用程序的偏好设置文件.可以使用NSUserDefaults类来获取和设置程序的偏好,会被iturns同步</ol>
    <ol>Caches : 用于存放应用程序专用的支持文件,保存应用程序再次启动过程中需要的信息,不会被iTunes备份同步</ol>
    <li>tmp: 存放临时数据,当不在用时应该删除掉临时文件,系统也有可能在程序不运行时删除该文件夹下内容</li>

    获取目录方法

    Documents目录

    <pre>`

    NSArray *documrntDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *pathfile = documrntDirectory.firstObject;

    `</pre>

    获取Library路径

    <pre>`NSArray*paths=NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES);

    NSString*path=[paths objectAtIndex:0];

    NSLog(@"path:%@",path); `</pre>

    获取Caches路径

    <pre>`NSArray*paths=NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);

    NSString*path=[paths objectAtIndex:0];

    NSLog(@"path:%@",path);`</pre>

    获取tmp路径

    <pre>`NSString*tmp=NSTemporaryDirectory();

    NSLog(@"tmp:%@",tmp);
    `</pre>

    文件写入

    <pre>`
    NSArray *documrntDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *pathfile = documrntDirectory.firstObject;
    [pathfile stringByAppendingPathComponent:@"feng.txt"];

    BOOL  ishave =  [[NSFileManager defaultManager]fileExistsAtPath:pathfile];
    if (!ishave) {
        NSLog(@"aleady have");
        return;
    }
     
    NSString *str  = @"im the king of the world";
    NSData *data  = [NSData dataWithContentsOfFile:str];
    BOOL result = [data writeToFile:pathfile atomically:YES];
    if (result) {
        NSLog(@"success");
        
    }else
    {
        NSLog(@"fail");
    }
    

    `</pre>

    文件读取

    <pre>`
    NSArray *documentsPathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [documentsPathArr lastObject];
    // 拼接要写入文件的路径
    NSString *path = [documentsPath stringByAppendingPathComponent:@"feng.txt"];
    // 从路径中读取字符串
    NSString *str = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@", str);

    `</pre>

    得到沙盒下所有文件

    <pre>`NSFileManager *fileManager = [NSFileManager defaultManager];

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

    `</pre>

    相关文章

      网友评论

          本文标题:沙盒

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