1
votes

I have a NSArray that contains dictionary objects. The structure of array looks like this:

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

I am using a Search and Display controller which allows the user to search through LotNumber, PartyName or Date. I know how to use Scope titles and search bar. However, I am unable to use NSPredicate to get correct results. This is my code:

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

I always get blank results in filtered array. Could you tell me what's wrong here?

Thank You.

1
Is LotNumber an NSNumber in the dictionary? - Wain
I set it using [dict setObject:lotNo forKey:@"LotNumber"]; . But even if its NSNumber, the above code doesn't work when I search for PartyName as well. - Gaurav Wadhwani
Have you debugged to check everything it set to the values you expect? - Wain
@Wain Yeah I NSLog'd the array which is not filtered, and it logs correct data to console. - Gaurav Wadhwani
Log the predicate too. - Wain

1 Answers

2
votes

You can use -predicateWithBlock: to filter your 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];
}