Search code examples
objective-ciosnsfilemanagernsdocumentdirectory

ios - removing any file, but not all files from the Document Directory


I have this code, which allows me to specify a particular file to be deleted from my documents directory.

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectoryPath = [[paths objectAtIndex:0] stringByAppendingString:@"/Podcasts"];

    NSString* checkIfFileExists = [documentsDirectoryPath stringByAppendingPathComponent:_fileName];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:checkIfFileExists error:NULL];

I can see this being useful if you want to delete a file with a button, but instead of wanting to only delete a particular file, how do I reference the removeItemAtPath: to handle any file within the array?? I do not want it to do delete all the files at once.


Solution

  • NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectoryPath = [[paths objectAtIndex:0] stringByAppendingString:@"/Podcasts"];
    NSString* checkIfFileExists = [documentsDirectoryPath stringByAppendingPathComponent:_fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isMyFileThere = [[NSFileManager defaultManager] fileExistsAtPath:checkIfFileExists];
    if(isMyFileThere){
    
              [fileManager removeItemAtPath:checkIfFileExists error:NULL];
    }
    else{
              //file dont exists
    }