简体   繁体   中英

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. 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.

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. In this case, there is no need to send retain to it either, since you are only using it locally within your method. You may want to review the Apple Developer Connection document " Cocoa Core Competencies: Memory Management ".

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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