美文网首页
NSFileManager操作小结

NSFileManager操作小结

作者: 朱益达 | 来源:发表于2016-08-04 14:26 被阅读36次

    16/08/04/wed

    NSFileManager操作小结:

    ① 直接在沙盒目录下添加文件: 此种情况下,沙盒路径下可以写入文件

        NSString *cachespath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
        NSString *local = [cachespath stringByAppendingPathComponent:@"heihei.txt"];
        NSString *test = @"this is a  test code";
       [test writeToFile:local atomically:YES encoding:NSUTF8StringEncoding error:nil];
    

    ② 在沙盒路径下自己添加文件夹:此种情况下,直接在自己拼接的路径下面写入文件是无效的

        NSString *cachespath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
        NSString *local = [cachespath stringByAppendingPathComponent:@"haha/heihei.txt"];
        NSString *test = @"this is a  test code";
       [test writeToFile:local atomically:YES encoding:NSUTF8StringEncoding error:nil];
       //这个路径不会创建,自然文件也不能写入进去
    

    对于②问题的解决办法是:自己拼接想要创建的路径,然后判断此路径是否存在,不存在的话就创建路径。再在路径下写入文件,代码如下

        NSString *cachespath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
        NSString *local = [cachespath stringByAppendingPathComponent:@"hehe/haha"];
        if (![[NSFileManager defaultManager] fileExistsAtPath:local]) {
            [[NSFileManager defaultManager] createDirectoryAtPath:local withIntermediateDirectories:YES attributes:nil error:nil];
        }
        NSString *final = [local stringByAppendingPathComponent:@"heihei.txt"];
        NSString *test = @"this is a  test code";
        [test writeToFile:final atomically:YES encoding:NSUTF8StringEncoding error:nil];
    

    相关文章

      网友评论

          本文标题:NSFileManager操作小结

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