Pregunta

I'm trying to read a full File/Folder Structure (starting from a given Folder) into an NSDictionary (with a NSArrays,etc), like this :

Let's say starting folder is : /Users/some-user/some-path

We go in there and list all folders/subfolders/files

A/

  • file_a.txt
  • file_b.txt
  • subfolder/
    • file_c.txt

B/

  • etc...

What I want is to convert this file structure (probably using enumerators and NSFileManager) into an NSDictionary like :

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

Any ideas?

¿Fue útil?

Solución

Well this is the working result :

To check if a path is a Directory/Package/Bundle, etc :

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

The actual function (using recursion) :

- (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;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top