获取文档目录中的目录数组

时间:2010-01-31 15:40:52

标签: iphone nsfilemanager

我正在尝试返回应用程序的Documents目录中的目录列表。我能够获得一个包含给定扩展名的所有文件的数组(例如.txt文件或.png文件),并且能够返回所有内容(包括目录)。当我想只返回目录时出现问题。有一种简单的方法吗?

以下是我返回所有.txt文件的代码:

- (ViewController *) init {
    if (self = [super init]) self.title = @"Text Files";

    // get the list of .txt files
    directoryList = [[[[NSFileManager defaultManager] directoryContentsAtPath:DOCUMENTS_FOLDER] 
                      pathsMatchingExtensions:[NSArray arrayWithObjects:@".txt", nil]] retain];
    NSLog(@"%@", directoryList);

    return self;
}

和所有文件

- (ViewController *) init {
    if (self = [super init]) self.title = @"Text Files";

    // get the list of all files and directories
    directoryList = [[[NSFileManager defaultManager] directoryContentsAtPath:DOCUMENTS_FOLDER] retain];

    NSLog(@"%@", directoryList);

    return self;
}

2 个答案:

答案 0 :(得分:22)

试试这个:

- (ViewController *) init {
    if (self = [super init]) self.title = @"Text Files";

    // get the list of all files and directories
    NSFileManager *fM = [NSFileManager defaultManager];
    fileList = [[fM directoryContentsAtPath:DOCUMENTS_FOLDER] retain];
    NSMutableArray *directoryList = [[NSMutableArray alloc] init];
    for(NSString *file in fileList) {
        NSString *path = [DOCUMENTS_FOLDER stringByAppendingPathComponent:file];
        BOOL isDir = NO;
        [fM fileExistsAtPath:path isDirectory:(&isDir)];
        if(isDir) {
            [directoryList addObject:file];
        }
    }

    NSLog(@"%@", directoryList);

    return self;
}

答案 1 :(得分:2)

Mrueg只写了一件事

fileList = [[fM directoryContentsAtPath:DOCUMENTS_FOLDER];

替换为

fileList = [fileManager contentsOfDirectoryAtPath:filePath error:nil];