-1

I have array of custom objects, _momsArray. shown here is single object of such array:

Custom *yourMom {
  name = @"Sally M. Brown";
  age = 54;
  weight = 43.2;
}

I run my predicate inside searchBar delegate:

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {

    if ([searchText length]<=0) {
        _tableDataArr = [[NSMutableArray alloc] initWithArray:_momsArray];
    } else{

        // filtered _tableDataArr
        NSString *filter = @"name BEGINSWITH[cd] %@";
        NSPredicate* predicate = [NSPredicate predicateWithFormat:filter, searchText];
        NSArray *filteredArr  = [_momsArray filteredArrayUsingPredicate:predicate];
        _tableDataArr = [[NSMutableArray alloc] initWithArray:filteredArr];
    }
    [_momTable reloadData];
}

This doesn't give expected result. For example, when I type S, sally doesn't appear at all. What is wrong with my code?

EDIT: The string in the custom objects contains punctuations and therefore it is not the same as other answers.

GeneCode
  • 7,545
  • 8
  • 50
  • 85

3 Answers3

1

Your string is not properly generated so use below code :

NSPredicate *predicate = [ NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", text];
arrFilterData = [NSArray arrayWithArray:[arrDataList filteredArrayUsingPredicate:predicate]];

OUTPUT

Before search

enter image description here

After search

enter image description here

And with code

NSPredicate *predicate = [ NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", text];
arrFilterData = [NSArray arrayWithArray:[arrDataList filteredArrayUsingPredicate:predicate]];

OutPut:

enter image description here

Edit

Output :

enter image description here

dahiya_boy
  • 9,298
  • 1
  • 30
  • 51
1

To filter an array with custom objects you can use this code.

NSString *str = @"text";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.name contains[c] %@", str];
NSArray *arrFiltered = [self.arrDataObject filteredArrayUsingPredicate:predicate];

Hope, it helps.

Sunny
  • 821
  • 6
  • 17
0

Use this code :

NSPredicate *pred = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@", searchText];
NSMutableArray *filteredArr = [[_momsArray filteredArrayUsingPredicate:pred]mutableCopy];
Niharika
  • 1,188
  • 15
  • 37