objective-c - 将文件树结构转换为 NSDictionary

标签 objective-c cocoa nsdictionary nsfilemanager property-list

我正在尝试将完整的文件/文件夹结构(从给定文件夹开始)读取到NSDictionary(带有NSArray等)中,如下所示:

假设起始文件夹是:/Users/some-user/some-path

我们进入那里并列出所有文件夹/子文件夹/文件

一个/

  • file_a.txt
  • file_b.txt
  • 子文件夹/
    • file_c.txt

B/

  • 等等...

我想要的是将此文件结构(可能使用枚举器和 NSFileManager)转换为 NSDictionary,如下所示:

<key>folder</key>
<string>A</string>
<key>values</key>
<array>
       <dict>
             <key>file</key>
             <string>file_a.txt</string>
             <key>url</key>
             <string>/Users/some-user/some-path/A/file_a.txt</string>
       </dict>
       <dict>
             <key>file</key>
             <string>file_b.txt</string>
             <key>url</key>
             <string>/Users/some-user/some-path/A/file_b.txt</string>
       </dict>
       <dict>
             <key>folder</key>
             <string>subfolder</string>
             <key>values</key>
             <array>
                       ...
             </array>
       </dict>

</array>

有什么想法吗?

最佳答案

这是工作结果:

检查路径是否是目录/包/ bundle 等:

- (BOOL)isDir:(NSString*)path
{
    BOOL isDir;
    if (([[NSFileManager defaultManager]
        fileExistsAtPath:path isDirectory:&isDir] && isDir) || 
        ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:path]))
              return YES;
    else
        return NO;
}

实际函数(使用递归):

- (NSArray*)getContents:(NSString*)path {

NSError* err = nil;
NSArray* files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&err];

NSMutableArray* conts = [[NSMutableArray alloc] initWithObjects: nil];

for (NSString* c in files)
{
    NSDictionary* d;

    NSString* p = [d stringByAppendingPathComponent:d];

    if (![self isDir:p])
    {
        d = [NSDictionary dictionaryWithObjectsAndKeys:
                           c,@"name",
                           p,@"url", nil];
    }
    else
    {
        d = [NSDictionary dictionaryWithObjectsAndKeys:
             c,@"group",
             p,@"entries", nil];
    }

    [conts addObject:d];
}

return conts;
}

关于objective-c - 将文件树结构转换为 NSDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9735622/

相关文章:

objective-c - NSArray 和快速枚举,总是按索引顺序进行?

objective-c - 在 ARC ObjectiveC++ 中使用 C++11 lambda 函数——如何正确使用?

cocoa - 在事件函数中更新 NSView

swift - 无法在 Label.text 中转换 NSString

ios - 重置 View 层次结构 iOS

objective-c - UIActivityViewController 在特定操作中使用项目

macos - Dropbox 如何将菜单项添加到 Finder 的上下文菜单?

objective-c - 如何隐藏/关闭 NSWindowController 及其 View ?

objective-c - NSDictionary 类的 JSONRepresentation 如何工作?

ios - 如何将字典的键转换为按字典中这些键对应的值排序的数组