3 回答

TA貢獻(xiàn)1863條經(jīng)驗(yàn) 獲得超2個贊
您可以借助NSPredicate輕松實(shí)現(xiàn)此目標(biāo),如下所示:
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];

TA貢獻(xiàn)1887條經(jīng)驗(yàn) 獲得超5個贊
這非常適合IOS,但也應(yīng)該適用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);
}
}

TA貢獻(xiàn)1719條經(jīng)驗(yàn) 獲得超6個贊
如何使用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
}
}
對于像這樣的簡單,直接的匹配,它比使用正則表達(dá)式庫更簡單。
- 3 回答
- 0 關(guān)注
- 771 瀏覽
添加回答
舉報(bào)