【问题标题】:Filter NSArray using NSPredicate [closed]使用 NSPredicate 过滤 NSArray [关闭]
【发布时间】:2013-05-31 08:21:02
【问题描述】:

我有一个包含字符串的数组。其中一些字符串可能为空 (@"")。谓词必须是什么样子才能过滤数组并返回一个仅包含非空字符串的新数组:

数组 A: {"A","B","","D"} -> 过滤器 -> 数组 B: {"A","B","D"}

它也应该返回这个:

数组 A:{"","","",""} -> 过滤器 -> 数组 B:{}

【问题讨论】:

    标签: ios objective-c nsarray nspredicate


    【解决方案1】:

    如果您只过滤NSStrings 的数组,请使用谓词SELF != ''。这匹配每个不完全等于空字符串的NSString

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF != ''"];
    NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate];
    

    示例代码:

    NSArray *array = @[@"A", @"B", @"", @"C", @"", @"D"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF != ''"];
    NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate];
    NSLog(@"Input array: %@\nFiltered array: %@", [array componentsJoinedByString:@","], [filteredArray componentsJoinedByString:@","]);
    

    给出这个输出

    Input array: A,B,,C,,D
    Filtered array: A,B,C,D
    

    编辑:Joris Kluivers 发布了谓词格式 length > 0 的解决方案。这可能是仅用于删除空字符串的更好解决方案,因为它可能会更快。

    【讨论】:

    • 像魅力一样工作:)
    【解决方案2】:

    检查字符串的长度:

    NSArray *values = @[@"A", @"B", @"", @"D"];
    NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"length > 0"];
    
    NSArray *filteredValues = [values filteredArrayUsingPredicate:filterPredicate];
    

    在所需的数组("A", "B", "C")中得到结果

    【讨论】:

    • +1 不错的解决方案,不知道这个。可能会比我的解决方案与空字符串比较快得多。我已经编辑了我的答案,提到了你的答案;-)
    【解决方案3】:
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c]%@",searchText];
    
    [arrSearched removeAllObjects];
    
    [arrSearched addObjectsFromArray:[self.arrContent filteredArrayUsingPredicate:predicate]];
    

    这里 arrContent 是原始数组,arrSearched 是搜索后的输出数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-11
      相关资源
      最近更新 更多