Huang
Huang

Reputation: 1355

NSPredicate to filter against a complete NSArray of strings, using nsstring

I need to filter a multi nested json that is basically an array of dictionary containing values for key that are also arrays

Here is a sample

{//Upper structure, an nsaaray of responses
Items =     (
            {
        descriptionRating = "some";
        category = 20;
    }
);
 dynamicVales =     (
    {
        text = "name";
        value = "falafel";
        type = 3;
    },
    {
        text = "name";
        value =       (
           turkeysandwich, 
           burger, 
           snickers
        );
        type = 2;
    },
    {
    text = "name";
        value = "whatever";
        type = 2;
    },

  );
},

so I have an nsarray of responses, each response has an nsarray of nsdictionaries in this case called "dynamicVales", this can contain one string or an array of strings, I need to filter all responses where a value in in dynamicVales = a string a value I have. That string is equal to the array

 NSString *selectedString = @"turkeysandwich, burger, snickers";

I tried this

[filteredresponses = self.responses filteredArrayUsingPredicate:[NSString 
 stringWithFormat:@"dynamicVales.value CONTAINS '%@'", selectedString];

obviously that is not working, is there a way of doing this in one predicate as opposed to me looping over these internal arrays?

   value =       (
           turkeysandwich, 
           burger, 
           snickers
        );

So in summary I need to filter that the entire contents of the string equal all contents of the NSArray in Value.

Upvotes: 0

Views: 688

Answers (2)

Jaimish
Jaimish

Reputation: 629

For your problem try the following code.

NSString *predicateString = [NSString stringWithFormat:@"ANY dynamicVales.value == 'chicken'"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];
NSArray *filteredResults = [Mainarray filteredArrayUsingPredicate:predicate];

You can see more syntax for the Predicate the arrays or Dictionaries, you can learn lot from below link:

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html#//apple_ref/doc/uid/TP40001795-SW1

Happy coding!

Upvotes: 4

Johnykutty
Johnykutty

Reputation: 12829

You can use predicateWithBlock method for creating your predicate. Inside the block, check whether the dynamicVale contains the value to be searched.

Code:

NSArray *yourArray = ....;
NSString *searchText = ...;

NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(NSDictionary   * _Nonnull evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
    NSArray *dynamicVales = [evaluatedObject valueForKeyPath: @"dynamicVales.value"];
    return [dynamicVales containsObject:searchText];

}];

NSArray *filteredArray = [yourArray filteredArrayUsingPredicate:predicate];

Upvotes: 0

Related Questions