I have an array with several NSString element in and I also have a view, where i have a search bar in. I want to begin searching for what the user writes in the search field as a substring for each NSString element. If the NSString element contains the substring, i want to add it to a new array. I have tried to do this with code, and it works okay, but it keep adding objects to, even it have already for them, so does anybody have any ideas why? I have already set the delegate to self.
//.h
@interface class1
@property(strong, nonatomic) NSMutableArray *allExercisesNames;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property(strong, nonatomic) NSMutableArray *foo;
@end
//.m
@implementation class1
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
for(int i = 0; i < _allExercisesNames.count;i++)
{
if([[_allExercisesNames objectAtIndex:i] rangeOfString:searchBar.text].location != NSNotFound)
{
if(_foo == nil)
{
_foo = [[NSMutableArray alloc]initWithObjects:[_allExercisesNames objectAtIndex:i], nil];
[self.gridView reloadData];
}
else
{
[_foo addObject:[_allExercisesNames objectAtIndex:i]];
[self.gridView reloadData];
}
}
}
if([searchBar.text isEqualToString:@""] || searchBar.text==nil)
//![_allExercisesNames containsObject:searchBar.text
{
_foo = nil;
[self.gridView reloadData];
}
}
You are not assigning ‘nil’ to _foo at the top of the function, so it continues adding to the old _foo array every time you type something.
Rather, you should set _foo to a new array at the top of the function instead, so it is cleared before scanning the _allExercisesNames array.
Here is a fixed, simplified version that also makes use of ‘for (x in y)’ to make it more concise.