12.5. Deleting Files and Folders


You have created some files and/or folders on disk and no longer need them, so you would like to delete them.


Use the removeItemAtPath:error: or the removeItemAtURL:error: instance method of the NSFileManager class. The former method takes the path as a string and the latter takes the path as a URL.


Deleting files and folders is perhaps one of the easiest operations that you can perform using a file manager. In iOS, you need to be mindful of where you store your files and folders in the first place, and once you have done the storage, you need to get rid of files and folders when you no longer need them. For instance, let’s create five text files in the tmp/text folder and then delete them once we are done. In the meantime, we can enumerate the contents of the folder before and after the deletion just to make sure things are working fine. Also, as you know, the tmp/ folder exists when your app is installed, but the tmp/text doesn’t. So we need to create it first. Once we are done with the files, we will delete the folder as well:

/* Creates a folder at a given path */
- (void) createFolder:(NSString *)paramPath{
    NSError *error = nil;
    if ([self.fileManager createDirectoryAtPath:paramPath
                                          error:&error] == NO){
        NSLog(@"Failed to create folder %@. Error = %@",

/* Creates 5 .txt files in the given folder, named 1.txt, 2.txt, etc */
- (void) createFilesInFolder: ...

Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.