'NSPredicate for @[@{@"someKey" : @"key"}] search for someKey

[
    {"theKeyOne"  :"One"},
    {"theKeyTwo"  :"Two"},
    {"theKeyThree":"Three"},
],

I want use String for predicateWithFormat to NSPredicate

for example

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%@ == %@)", @"theKeyTwo", @"theKeyTwo"];

the code, I think only output {"theKeyTwo" :"Two"}

but output allInfo.

the first Index is {"theKeyOne" :"One"} !!!

I want to get Two for theKeyTwo

I just know the

theKeyTwo

How should I use it for NSPredicate?



Solution 1:[1]

Well, try with this :)

    NSMutableDictionary *object1 = [[NSMutableDictionary alloc] init];
    [object1 setValue: @"One" forKey: @"theKeyOne"];
    [object1 setValue: @"Two" forKey: @"theKeyTwo"];
    [object1 setValue: @"Three" forKey: @"theKeyThree"];
    [object1 setValue: @"Four" forKey: @"theKeyFour"];

    // Getting the value using the key
    NSString *valueOfKey = [object1 valueForKey: @"theKeyTwo"];

    // Making the predicate using the value of key string
    NSPredicate *pred2 = [NSPredicate predicateWithFormat: @"theKeyTwo MATCHES[c] %@", valueOfKey];

Solution 2:[2]

The questions isn't so clear. Please pick one of my variants:

  1. If you want to substitute the key in a predicate, then you should use %K. So your predicate will look like this:

    [NSPredicate predicateWithFormat:@"%K = %@", @"theKeyTwo", @"Two"];

The output is an array: @[@{@"theKeyTwo": @"Two"}]

  1. To obtain only the value you should use valueForKeypath:

    NSArray *result = [yourArray valueForKeypath:@"theKeyTwo"]

The output is an array: @[@"Two"]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2