【问题标题】:filtering array with dictionaries using nspredicate fails使用 nspredicate 使用字典过滤数组失败
【发布时间】:2013-05-21 00:21:06
【问题描述】:

我正在尝试使用谓词从 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

【问题讨论】:

  • 字典中的值是 NSNumber 还是 NSString?
  • 发布问题后不会立即生效。编辑只是为了明确我为阅读它的人解决了它......

标签: cocoa nsarray nsdictionary nspredicate


【解决方案1】:

这对我有用:

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

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

【讨论】:

    【解决方案2】:

    显然,我把格式字符串弄错了。这有效:

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

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

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

    【讨论】:

    • 非常!这正是我想要的!
    猜你喜欢
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-18
    • 2015-07-02
    相关资源
    最近更新 更多