使用NSPredicate过滤NSFileManger内容以获取文件“模式”列表

时间:2013-07-29 06:24:02

标签: objective-c cocoa nspredicate nsfilemanager

我有一个字符串数组用作'过滤器':

@[@"*.png", @".DS_Store", @"Foobar", @".jpg"]

如何使用上述模式使用NSPredicate过滤掉文件夹的所有内容?

这是我到目前为止所得到的:

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

但这并没有给我我想要的结果。例如,png文件未被过滤。此外,我无法将其设置为不区分大小写,因此foobar不会被过滤掉。

2 个答案:

答案 0 :(得分:3)

查看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

答案 1 :(得分:0)

您可以过滤要列出的内容。剩余将自动过滤。

-(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);
}