0

i used the following method to delete all the contents of the folder

NSFileManager *fm = [NSFileManager defaultManager];
    NSArray* arrFilePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * strFilePath = [arrFilePath objectAtIndex:0];
    NSString *directory = [strFilePath stringByAppendingPathComponent:@"Electronic_Instrumentation-Sapna_publications"];
    NSError *error = nil;
    for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) 
    {
        directory = [directory stringByAppendingPathComponent:file];
        BOOL success = [fm removeItemAtPath:directory error:&error];
        file = nil;
        if (!success || error) 
        {
            NSLog(@"Failed to remove files");
        }
    }

but its deleting only first file in the directory

say i have 3 files in the dorectory file1.txt, file2.txt,file3.txt

when i call this method it ill delete only file1.txt but not other files , again if i call that method it ill delete file2.txt but not file3.txt

how can i fix this,,??

is there any way to delete a directory ?? thanx in advance

Ravi
  • 1,759
  • 5
  • 20
  • 38

1 Answers1

3

The problem is that you're changing directory the first time you go through your loop. Thereafter, you're using an invalid path. First time through the loop, directory has something like:

/path/to/the/file1.txt

The next time through the loop, you append the next file name, so directory becomes:

/path/to/the/file1.txt/file2.txt

That obviously won't work.

The best way to find a problem like this is to step through the code in the debugger, watching the relevant variables as you go.

The right way to fix this problem, now that you know what it is, is to stop modifying directory. You could use a temporary variable, like this:

for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) 
{
    NSString *path = [directory stringByAppendingPathComponent:file];
    BOOL success = [fm removeItemAtPath:path error:&error];

Or you could just use the result of -stringByAppendingPathComponent: as the argument to -removeItemAtPath:error:, like this:

for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) 
{
    BOOL success = [fm removeItemAtPath:[directory stringByAppendingPathComponent:file]
                                  error:&error];

is there any way to delete a directory ??

You could check the docs for -removeItemAtPath:error:. I'll save you a trip:

A path string indicating the file or directory to remove. If the path specifies a directory, the contents of that directory are recursively removed.

So yes, there is an easy way to delete a directory. Just specify the directory in the path argument to -removeItemAtPath:error:.

Caleb
  • 124,013
  • 19
  • 183
  • 272