Filter NSFileManger contents for a list of file 'patterns' using NSPredicate

一世执手 提交于 2019-12-24 21:28:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!