ios - 在 Xcode 项目中组织文件并以编程方式获取文件夹列表

标签 ios xcode cocoa-touch nsbundle

我在资源导航器中的 Xcode 项目中有以下结构,我想在我的应用程序中反射(reflect)出来。

enter image description here

也就是说,我想在“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/

相关文章:

ios - 按父标签对 UIPickerView 中的 JSON 数组进行排序

swift - Xcode 12 和 OSLog (os.log) : wrapping OSLogMessage causes compile error: Argument must be a string interpolation

objective-c - 由于内存警告而卸载 View Controller 时如何保留状态?

ios - 无法在 Xcode 11 中运行单元测试 : The run destination * is not valid for tests you have chosen to perform

iPhone 操作系统 3.0 文档集

objective-c - 如何在 UIScrollView 内的 UIWebView 上启用放大功能?

ios - 从预期返回非空值的方法返回 Nil

objective-c - 如何用apple bonjour for iOS读取TXT记录

ios - 'UIPopoverController' 已弃用 : first deprecated in iOS 9. 0

ios - NSAttributedString 相对字体大小自定义属性