Question

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.

Was it helpful?

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
}

OTHER TIPS

You can get the contents of a directory with - (NSArray *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error of NSFileManager.

https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html

Then loop over the array and delete the files one by one.

You can use the same code.

But need to add the file name to it like:

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

NSString* checkIfFileExists = [file stringByAppendingPathComponent:_fileName];

NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:checkIfFileExists error:NULL];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top