Filter NSFileManger contents for a list of file &#

2019-08-28 20:09发布

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.

2条回答
老娘就宠你
2楼-- · 2019-08-28 20:45

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);
}
查看更多
SAY GOODBYE
3楼-- · 2019-08-28 20:58

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
查看更多
登录 后发表回答