【问题标题】:Writing an NSPredicate that returns true if condition is not met编写一个 NSPredicate,如果条件不满足则返回 true
【发布时间】:2010-11-13 01:50:53
【问题描述】:

我目前有以下一段代码

NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF contains '-'"];
[resultsArray filterUsingPredicate:pred];

这将返回一个包含“-”元素的数组。我想做与此相反的操作,以便返回所有不包含 '-' 的元素。

这可能吗?

我尝试在不同位置使用 NOT 关键字,但无济于事。 (根据 Apple 文档,我不认为它会起作用)。

为了更进一步,是否可以为谓词提供一个我不想出现在数组元素中的字符数组? (数组是一堆字符串)。

【问题讨论】:

  • 更改了标题以更好地反映这个问题所问的内容。

标签: objective-c cocoa cocoa-touch nspredicate


【解决方案1】:

我不是 Objective-C 专家,但 documentation seems to suggest this is possible。你试过了吗:

predicateWithFormat:"not SELF contains '-'"

【讨论】:

  • 谢谢,因为我没有完整阅读文档。我唯一没有尝试过的地方是self之前!
【解决方案2】:

您可以构建一个自定义谓词来否定您已有的谓词。实际上,您正在获取一个现有谓词并将其包装在另一个类似于 NOT 运算符的谓词中:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF contains '-'"];
NSPredicate *notPred = [NSCompoundPredicate notPredicateWithSubpredicate:pred];
[resultsArray filterUsingPredicate:pred];

NSCompoundPredicate 类支持 AND、OR 和 NOT 谓词类型,因此您可以使用数组中不需要的所有字符构建一个大型复合谓词,然后对其进行过滤。尝试类似:

// Set up the arrays of bad characters and strings to be filtered
NSArray *badChars = [NSArray arrayWithObjects:@"-", @"*", @"&", nil];
NSMutableArray *strings = [[[NSArray arrayWithObjects:@"test-string", @"teststring", 
                   @"test*string", nil] mutableCopy] autorelease];

// Build an array of predicates to filter with, then combine into one AND predicate
NSMutableArray *predArray = [[[NSMutableArray alloc] 
                                    initWithCapacity:[badChars count]] autorelease];
for(NSString *badCharString in badChars) {
    NSPredicate *charPred = [NSPredicate 
                         predicateWithFormat:@"SELF contains '%@'", badCharString];
    NSPredicate *notPred = [NSCompoundPredicate notPredicateWithSubpredicate:pred];
    [predArray addObject:notPred];
}
NSPredicate *pred = [NSCompoundPredicate andPredicateWithSubpredicates:predArray];

// Do the filter
[strings filterUsingPredicate:pred];

不过,我不保证它的效率,最好将可能从最终数组中删除最多字符串的字符放在首位,以便过滤器可以短路尽可能多的比较.

【讨论】:

    【解决方案3】:

    我会推荐NSNotPredicateType,如Apple documentation 中所述。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-06
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      • 2021-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多