【问题标题】:contentsOfDirectoryAtPath with Contents of Subfolders objective-ccontentsOfDirectoryAtPath 与子文件夹的内容objective-c
【发布时间】:2013-10-19 19:18:51
【问题描述】:

如何获取目录及其所有子文件夹的内容?我想将树存储在NSDictionary

我希望字典打印如下内容:

{
    MyFolder =     (
        "Water.png",
                {
            MySubfolder =             (
                "Note.txt",
                                {
                    Sub-Subfolder =                     (
                        "3D.pdf",
                        "MyFile.txt"
                    );
                }
            );
        }
    );
}

我试过了:

NSFileManager *manager = [NSFileManager defaultManager];

    NSArray *array = [manager contentsOfDirectoryAtPath:path error:nil];
    NSMutableDictionary *files = [[NSMutableDictionary alloc]init];
            NSString  *newPath = @"";
    for (int i=0; array.count>i; i++) {

        newPath = [NSString stringWithFormat:@"%@/%@", path, [array objectAtIndex:i]];
        //echo(newPath);
        if ([[[manager attributesOfItemAtPath:newPath error:nil] objectForKey:NSFileType] isEqualToString:NSFileTypeRegular])
        {
            NSLog(@"Setting: %@||%@", [array objectAtIndex:i], [newPath lastPathComponent]);

            [files setObject:[array objectAtIndex:i] forKey:[newPath lastPathComponent]];


        }
        else
        {echo([NSString stringWithFormat:@"newPath=%@", newPath]);
            dict = [self reachedDirectory:newPath dict:dict oldPath:path];

        }


    }
    NSMutableDictionary *transferred = [dict objectForKey:[newPath lastPathComponent]];
    if (!transferred) {
        transferred = [[NSMutableDictionary alloc]init];
    }
    for (int n=0; files.count>n; n++) {
        [transferred setObject:[[files allValues] objectAtIndex:n] forKey:[[files allKeys] objectAtIndex:n]];
    }
    echo([newPath lastPathComponent]);
    [dict setObject:transferred forKey:[path lastPathComponent]];
    return dict;

但是所有的文件夹都没有对齐,并且没有超过子文件夹的第二个维度。我希望它能够拥有尽可能多的子文​​件夹。

感谢您的帮助!

【问题讨论】:

标签: objective-c macos nsarray nsdictionary nsfilemanager


【解决方案1】:

您可以使用 NSDirectoryEnumerator 类,它提供了 enumerateAtPath 方法,因此您只需传递主文件夹路径并在其中循环您的条件。这样无论您的子文件夹存在什么,它都会相应地打印路径。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多