我在资源导航器中的 Xcode 项目中有以下结构,我想在我的应用程序中反射(reflect)出来。
也就是说,我想在“Books”文件夹中“扫描”并获取其中所有文件夹的 NSArray
。下一步是我想获取每个文件夹中所有文件的 NSArray
。
到目前为止,我已经尝试使用任何连接到 NSBundle
的东西来获取文件夹列表,但这给了我错误的结果:
NSLog(@"bundle path is %@", [[NSBundle mainBundle] bundlePath]);
NSLog(@"resource path is %@", [[NSBundle mainBundle] resourcePath]);
这两种方法都没有以编程方式反射(reflect)实际的文件夹结构。
我们有什么办法可以做到这一点吗?
最佳答案
正如@rmaddy 指出的那样,您的 Xcode 项目中实际上应该有 blue 文件夹,然后使用 NSDirectoryEnumerator
获取所有文件夹的完整列表。
我是这样解决的:
NSURL *bundleURL = [[[NSBundle mainBundle] bundleURL] URLByAppendingPathComponent:@"Books" isDirectory:YES];
NSDirectoryEnumerator *dirEnumerator = [[NSFileManager defaultManager] enumeratorAtURL:bundleURL includingPropertiesForKeys:[NSArray arrayWithObjects:NSURLNameKey, NSURLIsDirectoryKey,nil] options:NSDirectoryEnumerationSkipsSubdirectoryDescendants errorHandler:nil];
for (NSURL *theURL in dirEnumerator){
// Retrieve the file name. From NSURLNameKey, cached during the enumeration.
NSString *folderName;
[theURL getResourceValue:&folderName forKey:NSURLNameKey error:NULL];
// Retrieve whether a directory. From NSURLIsDirectoryKey cached during the enumeration.
NSNumber *isDirectory;
[theURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:NULL];
if([isDirectory boolValue] == YES){
NSLog(@"Name of dir is %@", folderName);
}
}
关于ios - 在 Xcode 项目中组织文件并以编程方式获取文件夹列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29902228/