Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a directory and its contents using NSFileManager

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.

like image 818
booboo-a-choo Avatar asked Sep 08 '10 04:09

booboo-a-choo


People also ask

How do you remove a directory and all of its files?

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.

How do I delete contents of a folder?

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.

Which method is used to delete a directory?

os. rmdir() removes a file or a directory. The shutil. rmtree() method will delete a directory and the files contained in it.


2 Answers

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.

like image 150
Itai Ferber Avatar answered Oct 06 '22 01:10

Itai Ferber


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]; } 
like image 23
twerdster Avatar answered Oct 05 '22 23:10

twerdster