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.
To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.
Right-click the folder you want to delete and click Delete Folder. Click Yes to move the folder and its contents to the Deleted Items folder. When you empty the Deleted Items folder, everything in it — including any folders you've deleted — is permanently erased.
os. rmdir() removes a file or a directory. The shutil. rmtree() method will delete a directory and the files contained in it.
To start off, it would be wise to look through Apple's NSFileManager
documentation for the iPhone: NSFileManager Class Reference. Second, look at NSFileManager
's -removeItemAtPath:error:
method and its documentation. That's what you're looking for.
Heres some code I use that Ive edited to suit the question
- (NSMutableString*)getUserDocumentDir { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSMutableString *path = [NSMutableString stringWithString:[paths objectAtIndex:0]]; return path; } - (BOOL) createMyDocsDirectory { NSMutableString *path = [self getUserDocumentDir]; [path appendString:@"/MyDocs"]; NSLog(@"createpath:%@",path); return [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:NULL]; } - (BOOL) deleteMyDocsDirectory { NSMutableString *path = [self getUserDocumentDir]; [path appendString:@"/MyDocs"]; return [[NSFileManager defaultManager] removeItemAtPath:path error:nil]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With