由于某种疯狂的原因,我找不到一种方法来获取给定目录的带有glob的文件列表。
我现在遇到了一些类似的问题:
NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSArray *dirContents = [[NSFileManager defaultManager]
directoryContentsAtPath:bundleRoot];
然后..and去掉了我不想要的东西,这太糟糕了。但是我真正想要的是能够搜索像"foo*.jpg“这样的东西,而不是询问整个目录,但是我还没有能够找到这样的东西。
那么你到底是怎么做到的呢?
发布于 2009-05-25 17:15:13
在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];
发布于 2011-04-07 06:57:53
这在IOS
上工作得很好,但也应该在cocoa
上工作。
NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSFileManager *manager = [NSFileManager defaultManager];
NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:bundleRoot];
NSString *filename;
while ((filename = [direnum nextObject] )) {
//change the suffix to what you are looking for
if ([filename hasSuffix:@".data"]) {
// Do work here
NSLog(@"Files in resource folder: %@", filename);
}
}
发布于 2009-05-25 09:31:49
使用NSString的hasSuffix和hasPrefix方法怎么样?类似于(如果你在搜索"foo*.jpg"):
NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSArray *dirContents = [[NSFileManager defaultManager] directoryContentsAtPath:bundleRoot];
for (NSString *tString in dirContents) {
if ([tString hasPrefix:@"foo"] && [tString hasSuffix:@".jpg"]) {
// do stuff
}
}
对于像这样简单、直接的匹配,它将比使用regex库更简单。
https://stackoverflow.com/questions/499673
复制相似问题