问题
I've an array of strings to be used as a 'filter':
@[@"*.png", @".DS_Store", @"Foobar", @".jpg"]
How do I use above pattern to filter out all the contents of a folder using NSPredicate?
This is what I've got so far:
NSArray *contents = [fileManager contentsOfDirectoryAtPath:fullPath error:NULL];
NSArray *filter = @[@"*.png", @".DS_Store", @"Foobar", @".jpg"];
NSArray *contents = [contents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"((pathExtension IN[cd] %@) OR (lastPathComponent IN[cd] %@)) ", filter, filter]];
But this doesn't give me the result that I want. For an example png
files are not filtered. Also, I couldn't make this it case-insensitive so foobar
is not filtered out.
回答1:
Take a look at Predicate Programming Guide
NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"/Users/new/Desktop/" error:nil];
NSArray *extensions = [NSArray arrayWithObjects:@"jpg", @"png",nil];
NSArray *files = [contents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"!(pathExtension IN %@) AND !(self LIKE[c] %@)", extensions, @"Foobar"]];
//[c] for case insensitive
回答2:
You can filter those things you want to list. Remaining will automatically filtered.
-(void)filter
{
localSongs=[[NSMutableArray alloc]init];
NSArray * paths = NSSearchPathForDirectoriesInDomains ( NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
NSDirectoryEnumerator *de = [[NSFileManager defaultManager] enumeratorAtPath:documentsDirectory] ;
NSString *file;
while ((file = [de nextObject]))
if (([[file pathExtension] isEqualToString:@"MP3"]) || ([[file pathExtension]isEqualToString:@"mp4"]) || ([[file pathExtension]isEqualToString:@"mp3"]) || ([[file pathExtension]isEqualToString:@"mov"]) || ([[file pathExtension]isEqualToString:@"avi"]) )
[localSongs addObject:file.lastPathComponent];
NSLog(@"local files%@",localSongs);
}
来源:https://stackoverflow.com/questions/17917251/filter-nsfilemanger-contents-for-a-list-of-file-patterns-using-nspredicate