Iterating through files in a folder with nested folders - Cocoa

后端 未结 6 2104
迷失自我
迷失自我 2020-12-07 10:52

I need to access every file in a folder, including file that exist within nested folders. An example folder might look like this.

animals/
 -k.txt
 -d.jpg
 c         


        
6条回答
  •  星月不相逢
    2020-12-07 11:15

    Use NSDirectoryEnumerator to recursively enumerate files and directories under the directory you want, and ask it to tell you whether it is a file or directory. The following is based on the example listed at the documentation for -[NSFileManager enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:]:

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSURL *directoryURL = … // URL pointing to the directory you want to browse
    NSArray *keys = [NSArray arrayWithObject:NSURLIsDirectoryKey];
    
    NSDirectoryEnumerator *enumerator = [fileManager
        enumeratorAtURL:directoryURL
        includingPropertiesForKeys:keys
        options:0
        errorHandler:^BOOL(NSURL *url, NSError *error) {
            // Handle the error.
            // Return YES if the enumeration should continue after the error.
            return YES;
    }];
    
    for (NSURL *url in enumerator) { 
        NSError *error;
        NSNumber *isDirectory = nil;
        if (! [url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:&error]) {
            // handle error
        }
        else if (! [isDirectory boolValue]) {
            // No error and it’s not a directory; do something with the file
        }
    }
    

提交回复
热议问题