Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use an NSPredicate to detect NOT CONTAINS

I give up. I have tried every combination I can imagine to check if a string contains another string. Here's an example of intuitive syntax describing what I want to do:

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

Regardless of how I shift the NOT around, use the ! operator instead, shift the parentheses or remove them altogether, I always get an exception parsing this expression.

What is wrong with this expression?

EDIT: The exception happens when I call

[pMetadataQuery setPredicate:pPredicate];

and the exception is: * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unknown type of NSComparisonPredicate given to NSMetadataQuery (kMDItemFSName CONTAINS[c] "Some String")'

like image 860
vargonian Avatar asked Jul 13 '12 18:07

vargonian


2 Answers

I had complete success with:

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

The second two objects of the three in testArray ended up in filteredArray, under OS X v10.7 and iOS v4.3. So the issue isn't the predicate — making this technically a complete answer to the question — it's some sort of restriction in NSMetadataQuery. Sadly I've no experience in that area, but it's certainly the next thing to research.

like image 85
Tommy Avatar answered Sep 23 '22 19:09

Tommy


Swift 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)")
like image 31
Abhishek Jain Avatar answered Sep 22 '22 19:09

Abhishek Jain