NSPredicate以多个文件结尾

时间:2011-02-17 17:44:00

标签: iphone objective-c nspredicate

我正在尝试使用谓词检查以一组扩展名结尾的文件来过滤数组。我怎么能这样做?

接近'self的内容会在%@'中结束吗?谢谢!

NSArray * dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectoryPath error:nil];
NSArray * files = [dirContents filteredArrayUsingPredicate:
    [NSPredicate predicateWithFormat:@"self CONTAINS %@",
    [NSArray arrayWithObjects:@".mp4", @".mov", @".m4v", @".pdf", @".doc", @".xls", nil]
    ]];

2 个答案:

答案 0 :(得分:63)

您不希望包含要包含的数组。理想情况下,您还希望按路径扩展名进行过滤。所以

NSArray *extensions = [NSArray arrayWithObjects:@"mp4", @"mov", @"m4v", @"pdf", @"doc", @"xls", nil];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectoryPath error:nil];
NSArray *files = [dirContents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"pathExtension IN %@", extensions]];

答案 1 :(得分:3)

编辑马丁的答案远远优于此。他是正确的答案。


有几种方法可以做到这一点。可能最简单的只是构建一个巨大的OR谓词:

NSArray *extensions = [NSArray arrayWithObjects:@".mp4", @".mov", @".m4v", @".pdf", @".doc", @".xls", nil];
NSMutableArray *subpredicates = [NSMutableArray array];
for (NSString *extension in extensions) {
  [subpredicates addObject:[NSPredicate predicateWithFormat:@"SELF ENDSWITH %@", extension]];
}
NSPredicate *filter = [NSCompoundPredicate orPredicateWithSubpredicates:subpredicates];

NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectoryPath error:nil];
NSArray *files = [dirContents filteredArrayUsingPredicate:filter];

这将创建一个等同于:

的谓词
SELF ENDSWITH '.mp4' OR SELF ENDSWITH '.mov' OR SELF ENDSWITH '.m4v' OR ....