Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 541
Swissdude Avatar asked May 24 '26 03:05

Swissdude


2 Answers

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

like image 81
Swissdude Avatar answered May 27 '26 11:05

Swissdude


This works for me:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"email contains[c] %@",searchString];

filteredArray = [[NSMutableArray alloc] initWithArray: [[arrayData filteredArrayUsingPredicate:predicate] copy]];
like image 29
Rahul Bansal Avatar answered May 27 '26 11:05

Rahul Bansal