NSPredicate endswith multiple files

后端 未结 2 1117
走了就别回头了
走了就别回头了 2020-12-03 14:12

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 endswi

2条回答
  •  忘掉有多难
    2020-12-03 14:28

    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 ....
    

提交回复
热议问题