简体   繁体   English

NSFilemanager不创建文件

[英]NSFilemanager doesn't create file

I have a problem with NSFileManager, because i only can store a file into Application Documents Directory, but i want to create a file into a sub directory this i don't think why, i couldn't create. 我对NSFileManager有问题,因为我只能将文件存储到应用程序文档目录中,但是我想将文件创建到子目录中,这我不认为为什么,我无法创建。 my code below: 我的代码如下:

+(NSString *)applicationDocumentsDirectory {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}

+(BOOL)storeFile:(NSData*)file withName:(NSString*)name atDirectory:(NSString*)dir{

    NSFileManager *filemgr;
    NSString *docsDir;
    NSString *newDir;
    BOOL create=NO;
    filemgr =[NSFileManager defaultManager];


    docsDir = [StorageManager applicationDocumentsDirectory];

    newDir = [docsDir stringByAppendingPathComponent:dir];

    if(![filemgr fileExistsAtPath:newDir]){
        if([filemgr createDirectoryAtPath:newDir withIntermediateDirectories:NO attributes:nil  error:nil]){
            create=YES;
        }    
    }else
        create=YES;

    if(create){
        if(![filemgr createFileAtPath:newDir contents:file attributes:nil]){
            [filemgr release];
            return YES;
        }
    }

        [filemgr release];
    return NO;
}

I am not sure why the file is not created. 我不确定为什么不创建文件。 At first glance, it looks like your code should work. 乍一看,您的代码应该可以正常工作。 But I may be overlooking something. 但是我可能忽略了一些东西。 It also depends on what exactly you are passing as arguments to the storeFile:withName:atDirectory: method. 它还取决于您究竟将什么作为参数传递给storeFile:withName:atDirectory:方法。

Nevertheless I am posting an answer because I did spot another error in your code: you should not send release to filemgr since you also did not send retain to it first and you did not create the object. 应该派:不过,因为我没有发现其他错误在你的代码我张贴的答案releasefilemgr因为你还没有送retain它首先和你没有创建对象。 In this case, there is no need to send retain to it either, since you are only using it locally within your method. 在这种情况下,也不需要向其发送retain ,因为您仅在方法内部本地使用它。 You may want to review the Apple Developer Connection document " Cocoa Core Competencies: Memory Management ". 您可能需要查看Apple Developer Connection文档“ Cocoa核心能力:内存管理 ”。

I don't think this error explains why the file is not created; 我不认为此错误可以解释为什么未创建文件。 though I'm surprised your application doesn't crash because of it. 尽管我很惊讶您的应用程序不会因此而崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM