1

我有一个包含字典对象的 NSArray。数组的结构如下所示:

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

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

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

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

谢谢你。

4

1 回答 1

2

您可以使用-predicateWithBlock:过滤您的 dataArray

- (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];
}
于 2014-05-05T06:45:04.353 回答