Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering NSDictionary with predicate

I am using a NSDictionary that itself contains dictionaries some keys and its values.The format is like ,

{

"1" = {
        "key1" = "ss",
          "key2" = "rr",
          "name" = "nm"
     },
"2" = {
           "key1" = "tt",
          "key2" = "vv",
           "name" = "gf"
     },
"3" = {
           "key1" = "nm",
          "key2" = "vv",
           "name" = "gf"
     },
"4" = {
           "key1" = "tt",
          "key2" = "vv",
          "name" = "gf"
     },
}

I need to filter with the case that key1 should be "tt" and key2 should "vv" using NSPredicate.

like image 608
Nassif Avatar asked May 15 '13 04:05

Nassif


1 Answers

Assume that

mainDict = {

"1" = {
        "key1" = "ss",
          "key2" = "rr",
          "name" = "nm"
     },
"2" = {
           "key1" = "tt",
          "key2" = "vv",
           "name" = "gf"
     },
"3" = {
           "key1" = "nm",
          "key2" = "vv",
           "name" = "gf"
     },
"4" = {
           "key1" = "tt",
          "key2" = "vv",
          "name" = "gf"
     },
}

Now you can filter by the following way:

NSArray *resultArray = [[mainDict allValues] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(key1 == %@) AND (key2==%@)", @"tt",@"vv"]];

try this to check:

NSMutableDictionary *mainDict=[[NSMutableDictionary alloc] init];
for(int i=1; i<=3; i++)
{
    [mainDict setObject:[NSDictionary dictionaryWithObjectsAndKeys:@"tt",@"key1",@"vv",@"key2",@"ttqwdwd",@"name", nil] forKey:[NSString stringWithFormat:@"%i",i]];
}
[mainDict setObject:[NSDictionary dictionaryWithObjectsAndKeys:@"tt",@"key1",@"kk",@"key2",@"ttwwdwd",@"name", nil] forKey:[NSString stringWithFormat:@"%i",4]];
[mainDict setObject:[NSDictionary dictionaryWithObjectsAndKeys:@"tt",@"key1",@"kk",@"key2",@"ttwwdwd",@"name", nil] forKey:[NSString stringWithFormat:@"%i",5]];
NSArray *resultArray = [[mainDict allValues] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(key1 == %@) AND (key2==%@)", @"tt",@"vv"]];
NSLog(@"%@",resultArray);
like image 81
Loquatious Avatar answered Oct 01 '22 20:10

Loquatious