Get array of directories in documents directory

会有一股神秘感。 提交于 2019-12-03 13:03:52

问题


I am trying to return the list of directories present in an app's Documents directory. I am able to get an array containing all files of a given extension (eg .txt files or .png files) and am able to return all contents (including directories). The problem arises when I want to return only the directories. Is there a simple way of doing this?

Here is my code for returning all .txt files:

- (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;
}

and for all of the files

- (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;
}

回答1:


Try this:

- (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;
}



回答2:


Mrueg wrote it all but one thing that

fileList = [[fM directoryContentsAtPath:DOCUMENTS_FOLDER];

Replace by

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


来源:https://stackoverflow.com/questions/2172245/get-array-of-directories-in-documents-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!