How to remove a directory and its contents using NSFileManager

Viewed 35705

New to Objective C. I have created a few directories which contain pdf files for an iPhone app. How can I delete a directory and its contents using NSFileManager?

Do I need to loop through and remove the contents first? Any code samples would be much appreciated.

Thanks in advance.

3 Answers

You can get document directory by using this:

NSString *directoryPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/"];

** Remove full directory path by using this:

BOOL success = [fileManager removeItemAtPath:directoryPath error:nil];
if (!success) {
    NSLog(@"Directory delete failed");
}

** Remove the contents of that directory using this:

NSFileManager *fileManager = [NSFileManager defaultManager];    
if ([fileManager fileExistsAtPath:directoryPath]) {
            NSDirectoryEnumerator *dirEnum = [fileManager enumeratorAtPath:directoryPath];
            NSString *documentsName;
            while (documentsName = [dirEnum nextObject]) {
                NSString *filePath = [directoryPath stringByAppendingString:documentsName];
                BOOL isFileDeleted = [fileManager removeItemAtPath:filePath error:nil];
                if(isFileDeleted == NO) {
                    NSLog(@"All Contents not removed");
                    break;
                }
            }
            NSLog(@"All Contents Removed");
        }

** You can edit directoryPath as per your requirement.

Related