ios - 使用 glob 获取目录中的文件列表

由于某种疯狂的原因,我找不到一种方法来获取给定目录的带有 glob 的文件列表。

我目前遇到以下问题:

NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSArray *dirContents = [[NSFileManager defaultManager] 
                        directoryContentsAtPath:bundleRoot];

..然后去掉我不想要的东西,这很糟糕。但我真正想要的是能够搜索“foo*.jpg”之类的东西,而不是要求整个目录,但我一直找不到类似的东西。

那么你是怎么做到的呢?

最佳答案

您可以在 NSPredicate 的帮助下轻松实现这一点,如下所示:

NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *dirContents = [fm contentsOfDirectoryAtPath:bundleRoot error:nil];
NSPredicate *fltr = [NSPredicate predicateWithFormat:@"self ENDSWITH '.jpg'"];
NSArray *onlyJPGs = [dirContents filteredArrayUsingPredicate:fltr];

如果你需要用 NSURL 来代替它看起来像这样:

NSURL *bundleRoot = [[NSBundle mainBundle] bundleURL];
NSArray * dirContents = 
      [fm contentsOfDirectoryAtURL:bundleRoot
        includingPropertiesForKeys:@[] 
                           options:NSDirectoryEnumerationSkipsHiddenFiles
                             error:nil];
NSPredicate * fltr = [NSPredicate predicateWithFormat:@"pathExtension='jpg'"];
NSArray * onlyJPGs = [dirContents filteredArrayUsingPredicate:fltr];

https://stackoverflow.com/questions/499673/

相关文章:

ios - 如何在 UILabel 中嵌入小图标

iphone - 错误 : The service is invalid

iphone - 什么是使 iOS 应用程序崩溃的可靠方法?

ios - 如何使 UIButton 文本对齐中心?使用 IB

objective-c - Objective-C 中的 MD5 算法

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

objective-c - 关于iOS5 SDK中自动引用计数的一些问题

objective-c - 使用 NSLocalizedString 的最佳实践

objective-c - iOS 7 sizeWithAttributes : replaceme

iphone - 以编程方式选择 tableview 行