< Previous PageNext Page > Hide TOC

Enumerating A Directory

You use an NSDirectoryEnumerator object to enumerate the contents of a directory. It returns the pathnames of all files and directories contained within that directory. The pathnames are relative to the directory. This enumeration is recursive, including the files of all subdirectories, and crosses device boundaries. It does not resolve symbolic links or attempt to traverse symbolic links that point to directories.

NSDirectoryEnumerator is an abstract class, a cover for a private concrete subclass tailored to the file system’s directory structure. You cannot create an NSDirectoryEnumerator object directly—you use NSFileManager’s enumeratorAtPath: method to retrieve a suitable instance.

To get the next item from the NSDirectoryEnumerator, invoke the NSEnumerator method nextObject. The methods declared by NSDirectoryEnumerator return attributes—both of the parent directory and the current file or directory—and allow you to control recursion into subdirectories.

The following example enumerates the contents of the user’s home directory and processes files; if, however, it comes across RTFD file packages, it skips recursion into them:

NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager]
        enumeratorAtPath:NSHomeDirectory()];
NSString *pname;
while (pname = [direnum nextObject])
{
    if ([[pname pathExtension] isEqualToString:@"rtfd"])
    {
         /* don't enumerate this directory */
         [direnum skipDescendents];
    }
    else
    {
        /* ...process file here... */
    }
}


< Previous PageNext Page > Hide TOC


© 1997, 2009 Apple Inc. All Rights Reserved. (Last updated: 2009-03-05)


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.