NSPredicate endswith multiple files

Soch S. picture Soch S. · Feb 17, 2011 · Viewed 9.3k times · Source

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:
    [NSPredicate predicateWithFormat:@"self CONTAINS %@",
    [NSArray arrayWithObjects:@".mp4", @".mov", @".m4v", @".pdf", @".doc", @".xls", nil]
    ]];

Answer

Martin Pilkington picture Martin Pilkington · Feb 17, 2011

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