12.4. Enumerating Files and Folders


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.


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 = [[NSFileManager alloc] init];
NSString *bundleDir = [[NSBundle mainBundle] bundlePath];

NSError *error = nil;
NSArray *bundleContents = [fileManager contentsOfDirectoryAtPath:bundleDir

if ([bundleContents count] > 0 &&
    error == nil){
    NSLog(@"Contents of the app bundle = %@", bundleContents);
else if ([bundleContents count] == 0 &&
         error == nil){
    NSLog(@"Call the police! The app bundle is empty.");
else {
    NSLog(@"An error happened = %@", error);


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. ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.