使用一个NSPredicate为NOT CONTAINS检测(Use an NSPredicate

2019-09-19 11:14发布

我放弃。 我想尽组合,我可以想像,以检查是否一个字符串包含另一个字符串。 下面是直观的语法描述什么我想要做的一个例子:

    NSPredicate* pPredicate = [NSPredicate predicateWithFormat:@"NOT (%K CONTAINS[c] %@)",
NSMetadataItemFSNameKey, 
[NSString stringWithFormat:@"Some String"]];

不管我如何转移不在身边,使用! 操盘手,却将括号或完全删除它们,我总是得到一个异常解析这个表达式。

什么是错的这个表情?

编辑:当我打电话的异常情况

[pMetadataQuery setPredicate:pPredicate];

和例外是:*终止应用程序由于未捕获的异常“NSInvalidArgumentException”,原因:“给予NSMetadataQuery(kMDItemFSName CONTAINS并[c]‘一些字符串’)未知的类型NSComparisonPredicate的”

Answer 1:

我曾与圆满成功:

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"NOT (%K CONTAINS[c] %@)",
        @"someKey",
        [NSString stringWithFormat:@"Some String"]];
NSArray *testArray =
    [NSArray arrayWithObjects:
        [NSDictionary dictionaryWithObject:@"This sure is Some String" forKey:@"someKey"],
        [NSDictionary dictionaryWithObject:@"I've nothing to say" forKey:@"someKey"],
        [NSDictionary dictionaryWithObject:@"I don't even have that key" forKey:@"someOtherKey"],
        nil];

NSArray *filteredArray = [testArray filteredArrayUsingPredicate:predicate];
NSLog(@"found %@", filteredArray);

在三者的第二两个对象testArray结束了在filteredArray ,在OS X v10.7和iOS V4.3。 所以,问题的关键不是谓语-使这在技术上完全解决这个问题-这是某种形式的限制NSMetadataQuery 。 可悲的是我有没有这方面的经验,但它肯定是研究未来的事情。



Answer 2:

雨燕3.0

let predicate = NSPredicate(format: "NOT (%K CONTAINS[c] %@)", "someKey", "Some String")
let testArray: [Any] = [[ "someKey" : "This sure is Some String" ], [ "someKey" : "I've nothing to say" ], [ "someOtherKey" : "I don't even have that key" ]]
let filteredArray: [Any] = testArray.filter { predicate.evaluate(with: $0) }
print("found \(filteredArray)")


文章来源: Use an NSPredicate to detect NOT CONTAINS