开发者

NSPredicate endswith multiple files

开发者 https://www.devze.com 2023-02-11 12:13 出处:网络
I am trying to filter an array using a predicate checking for files ending in a set of extensions. How could I do it?

I am trying to filter an array using a predicate checking for files ending in a set of extensions. How could I do it?

Would something close to 'self endswith in %@' work? Thanks!

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


You don't want contains for an array, you want in. You also ideally want to filter by the path extension. So

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]];


edit Martin's answer is far superior to this one. His is the correct answer.


There are a couple ways to do it. Probably the simplest would just be to build a giant OR predicate:

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];

This will create a predicate that's equivalent to:

SELF ENDSWITH '.mp4' OR SELF ENDSWITH '.mov' OR SELF ENDSWITH '.m4v' OR ....
0

精彩评论

暂无评论...
验证码 换一张
取 消