使用nspredicate过滤带字典的数组失败

时间:2013-05-25 15:47:23

标签: cocoa nsarray nsdictionary nspredicate

我正在尝试使用谓词从NSMutableArray中获取NSDictionary:

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

任何想法我做错了???

[已解决]显然,我使格式字符串错误。这有效:

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

根据这篇文章NSPredicate predicateWithFormat passing in name of attribute

对于密钥或密钥路径,必须使用@K

2 个答案:

答案 0 :(得分:8)

显然,我使格式字符串错误。这有效:

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

根据这篇文章NSPredicate predicateWithFormat传递属性名称

对于密钥或密钥路径,必须使用@K

答案 1 :(得分:1)

这对我有用:

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

filteredArray = [[NSMutableArray alloc] initWithArray: [[arrayData filteredArrayUsingPredicate:predicate] copy]];