NSPredicate endswith multiple files

后端 未结 2 1089
走了就别回头了
走了就别回头了 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:25

    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]];
    
    0 讨论(0)
  • 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 ....
    
    0 讨论(0)
提交回复
热议问题