hds
hds

Reputation: 33

Search bar delegate

Here is my code :

- (void)searchTextDidChange:(TaggingSearchBar *)searchBar
                       text:(NSString *)searchText {


    NSArray *allPlayers = self.sessionModel.taggingModel.PlayersFromDatabase;
    [self.filterdPlayers removeAllObjects];
    if (searchText.length > 0) {
        self.isFilterd = YES;
        for (Player *p in allPlayers) {
            NSString *playerDescription = [NSString stringWithFormat:@"%d %@", p.jerseyNumber.intValue, p.fullName];
            if ([playerDescription rangeOfString:searchText].location != NSNotFound) {
                [self.filterdPlayers addObject:playerDescription];
            }
        }
    }
    else {
        self.filterdPlayers = [allPlayers mutableCopy];
        self.isFilterd = NO ;
    }
}

Something is wrong because when I'm debugging and I put C (I have a person with the name Cat ) i get nil in self.filtredPlayers. Debugger showed hat stood in this place , and if all ok but nothing happened. What could cause this ? I tried containsstring + addObject:p

Upvotes: 0

Views: 97

Answers (2)

Reshmi Majumder
Reshmi Majumder

Reputation: 961

Use This

NSString *search_str = [NSString stringWithFormat:@"%@%@",searchBar.text, searchText];

   if ( playerDescription.containsString(searchBar.text)) //instead of  if ([playerDescription rangeOfString:searchText].location != NSNotFound)

Upvotes: 0

Aviram
Aviram

Reputation: 3067

The code looks fine in terms of functionality. To be on the safe side, I would change the inner if clause to this:

if (searchText && [playerDescription rangeOfString:searchText].length) {

This is safer, because if searchText is nil, your code would crash. I understand that you verify it before, but it's the best practice.

Moreover, I think your problem is due to the fact that you add the string object, instead of the Player object. When the search term is empty/nil, you add the Player objects:

self.filterdPlayers = [allPlayers mutableCopy];

But when the search term exists, you add the string playerDescription instead of the Player object:

[self.filterdPlayers addObject:p];

Upvotes: 2

Related Questions