14.5. Deleting Files and Folders
Problem
You have created some files and/or folders on disk and no longer need them, so you would like to delete them.
Solution
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.
Discussion
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 folder 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.fileManagercreateDirectoryAtPath:paramPathwithIntermediateDirectories:YESattributes:nilerror:&error]==NO){NSLog(@"Failed to create folder %@. Error = %@",paramPath,error);}}/* Creates 5 .txt files in the given folder, named 1.txt, 2.txt, etc */-(void)createFilesInFolder: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access