【问题标题】:NSPredicate endswith multiple filesNSPredicate 以多个文件结尾
【发布时间】:2011-02-17 17:44:00
【问题描述】:

我正在尝试使用谓词检查以一组扩展名结尾的文件来过滤数组。我怎么能做到?

在 %@' 中接近 'self 的东西会起作用吗?谢谢!

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

【问题讨论】:

    标签: iphone objective-c nspredicate


    【解决方案1】:

    您不希望包含数组,而是希望在其中。理想情况下,您还希望按路径扩展名进行过滤。所以

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

    【讨论】:

    • +1 远远优于我的回答。我不敢相信我没有想到这一点。向你致敬。
    【解决方案2】:

    edit Martin 的回答远远优于这个。他的答案是正确的。


    有几种方法可以做到这一点。可能最简单的就是构建一个巨大的 OR 谓词:

    NSArray *extensions = [NSArray arrayWithObjects:@".mp4", @".mov", @".m4v", @".pdf", @".doc", @".xls", nil];
    NSMutableArray *subpredicates = [NSMutableArray array];
    for (NSString *extension in extensions) {
      [subpredicates addObject:[NSPredicate predicateWithFormat:@"SELF ENDSWITH %@", extension]];
    }
    NSPredicate *filter = [NSCompoundPredicate orPredicateWithSubpredicates:subpredicates];
    
    NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectoryPath error:nil];
    NSArray *files = [dirContents filteredArrayUsingPredicate:filter];
    

    这将创建一个谓词,相当于:

    SELF ENDSWITH '.mp4' OR SELF ENDSWITH '.mov' OR SELF ENDSWITH '.m4v' OR ....
    

    【讨论】:

      猜你喜欢
      • 2017-03-07
      • 2020-11-24
      • 2011-05-13
      • 2012-09-30
      • 2022-01-20
      • 2016-12-22
      • 2012-04-25
      • 1970-01-01
      相关资源
      最近更新 更多