12.4. Enumerating Files and Folders
Problem
You either want to enumerate folders within a folder or you want to enumerate the list of files inside a folder. The act of enumerating means that you simply want to find all the folders and/or files within another folder.
Solution
Use the contentsOfDirectoryAtPath:error: instance
method of the NSFileManager class as
shown here. In this example, we are enumerating all the files, folders,
and symlinks under our app’s bundle folder:
NSFileManager*fileManager=[[NSFileManageralloc]init];NSString*bundleDir=[[NSBundlemainBundle]bundlePath];NSError*error=nil;NSArray*bundleContents=[fileManagercontentsOfDirectoryAtPath:bundleDirerror:&error];if([bundleContentscount]>0&&error==nil){NSLog(@"Contents of the app bundle = %@",bundleContents);}elseif([bundleContentscount]==0&&error==nil){NSLog(@"Call the police! The app bundle is empty.");}else{NSLog(@"An error happened = %@",error);}
Discussion
In some of your iOS apps, you may need to enumerate the contents of a folder. Let me give you an example, in case this need is a bit vague right now. Imagine that the user asked you to download 10 images from the Internet and cache them in your app. You go ahead and save them, let’s say, in the tmp/images/ folder that you manually created. Now the user closes your app and reopens it, and in your UI, you want to display the list of already-downloaded-files in a table view. How can you achieve this? Well, it’s easy. ...
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