【问题标题】:File Tree Structure into NSDictionary文件树结构到 NSDictionary
【发布时间】:2012-03-16 10:30:29
【问题描述】:

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

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

我们进去并列出所有文件夹/子文件夹/文件

A/

  • 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>

有什么想法吗?

【问题讨论】:

  • 我看到你已经用nsfilemanager 标记了这个问题。 nsfilemanager 拥有你完成这项任务所需的所有方法,所以我不确定你还需要知道什么。
  • 好吧,事实上,我设法做到了(我稍后会发布完整的答案);但是,我在检查路径是否是文件夹时仍然遇到问题......你能帮我解决这个问题吗? stackoverflow.com/questions/9736696/…

标签: objective-c cocoa nsdictionary nsfilemanager property-list


【解决方案1】:

这就是工作的结果:

检查path 是否是目录/包/捆绑包等:

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

【讨论】:

    猜你喜欢
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 2015-03-30
    • 2022-12-12
    相关资源
    最近更新 更多