【问题标题】:Filtering NSArray with NSDictionary Objects using NSPredicate使用 NSPredicate 过滤带有 NSDictionary 对象的 NSArray
【发布时间】:2013-11-20 06:32:57
【问题描述】:

我有一个包含字典对象的 NSArray。数组的结构是这样的:

Data = (
    {
    Date = "07/11/2013";
    LotNumber = 1;
    PartyName = "Gaurav Wadhwani";
    Quantity = 500;
},
    {
    Date = "07/11/2013";
    LotNumber = 2;
    PartyName = "Gaurav Wadhwani";
    Quantity = 600;
}
)

我正在使用搜索和显示控制器,它允许用户搜索 LotNumberPartyNameDate。我知道如何使用范围标题和搜索栏。但是,我无法使用 NSPredicate 来获得正确的结果。这是我的代码:

NSString *searchParameter = @"LotNumber";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K contains[cd] %@", searchParameter, searchText];
    filteredGoodsArray = [NSMutableArray arrayWithArray:[data filteredArrayUsingPredicate:predicate]];
NSLog(@"Filtered Array = %@", filteredGoodsArray);

我总是在过滤后的数组中得到空白结果。你能告诉我这里有什么问题吗?

谢谢。

【问题讨论】:

  • 字典中有LotNumberNSNumber 吗?
  • 我使用 [dict setObject:lotNo forKey:@"LotNumber"]; .但是即使它的 NSNumber,当我搜索 PartyName 时,上面的代码也不起作用。
  • 您是否进行了调试以检查它设置为您期望的值的所有内容?
  • @Wain 是的,我 NSLog'd 未过滤的数组,并将正确的数据记录到控制台。
  • 也记录谓词。

标签: objective-c nsarray nspredicate


【解决方案1】:

您可以使用 -predicateWithBlock: 来过滤您的数据数组

- (NSArray *)filterArray:(NSArray *)dataArray WithSearchText:(NSString *)searchText ScopeTitle:(NSString *)scopeTitle {
    NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        //this is the dictionary in your dataArray
        NSDictionary *dictionary = (NSDictionary *)evaluatedObject;
        NSString *key = @"";

        //get key based on your selected scope
        if ([scopeTitle isEqualToString:@"Lot"])
            key = @"LotNumber";
        else if ([scopeTitle isEqualToString:@"Party"])
            key = @"PartyName";

        //grab the value from the dictionary with the corresponding key
        NSString *value = [dictionary objectForKey:key];

        //if the value contains your searchText return YES to add the object to the filtered array
        //if not it returns NO to filter it out of the array
        return [value rangeOfString:searchText options:NSCaseInsensitiveSearch].location != NSNotFound;
    }];

    //filter your dataArray using the predicate
    return [dataArray filteredArrayUsingPredicate:predicate];
}

【讨论】:

    猜你喜欢
    • 2012-05-17
    • 2012-08-02
    • 2010-10-31
    • 2016-09-29
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多