我正在尝试将完整的文件/文件夹结构(从给定的文件夹开始)读入NSDictionary
(带有NSArray
s等),如下所示:
假设起始文件夹是:/ Users / some-user / some-path
我们进去并列出所有文件夹/子文件夹/文件
A /
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>
有什么想法吗?
答案 0 :(得分: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;
}