由于某种疯狂的原因,我找不到一种方法来获取给定目录的带有 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];
关于ios - 使用 glob 获取目录中的文件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/499673/