Search code examples
cocoansarraynsdictionarynspredicate

filtering array with dictionaries using nspredicate fails


I'm trying to get an NSDictionary out of an NSMutableArray using a predicate:

NSMutableArray *arr = [NSMutableArray arrayWithArray:[self createArrayFromCSV:savedCSV withDelimiter:delim firstLineContainsKeys:YES]];

// The method «createArrayFromCSV returns an array of dictionaries

NSLog(@"Array %@", [arr objectAtIndex:0]);  // works fine

// spits out: 

// Array {
//     product = "MyProduct";
//     "id_product" = 29;
// }

// idField and idVal are passed to the method

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

NSLog(@"predicate %@", predicate);

// spits out predicate "id_product" == "29"

NSArray *filtered = [arr filteredArrayUsingPredicate:predicate];

NSLog(@"Filtered %@", filtered);

// Filtered is always empty

Any ideas what I'm doing wrong???

[SOLVED] Apparently, I made the format string wrong. This works:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%K == %@)", idField, idVal];

According to this post NSPredicate predicateWithFormat passing in name of attribute

for keys or keypaths, one has to use @K


Solution

  • Apparently, I made the format string wrong. This works:

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%K == %@)", idField, idVal];
    

    According to this post NSPredicate predicateWithFormat passing in name of attribute

    for keys or keypaths, one has to use @K