3 回答

TA貢獻1863條經驗 獲得超2個贊
您可以借助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];

TA貢獻1887條經驗 獲得超5個贊
這非常適合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);
}
}

TA貢獻1719條經驗 獲得超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
}
}
對于像這樣的簡單,直接的匹配,它比使用正則表達式庫更簡單。
- 3 回答
- 0 關注
- 773 瀏覽
添加回答
舉報