Reputation: 4235
I'm new with UISearchBar and i've got some code for searching words.
- (void)searchTableView
{
NSLog(@"Searching...");
NSString *searchText = searchBar.text;
NSMutableArray *tempSearch = [[NSMutableArray alloc] init];
for (NSDictionary *item in items) {
if ([[item objectForKey:@"en"] isEqualToString:searchText]) {
NSLog(@"Found");
[tempSearch addObject:item];
}
}
searchArray = [tempSearch copy];
}
It works but problem is it works only for complete word (e.g. If in textLabel
in UITableViewCell
is text "something" and i type "something" in UISearchBar
then i've got this row returned, but when i type "some" i've got rows when complete word is "some", "something" isn't showed). How can i search text correclty with my method?
Upvotes: 0
Views: 93
Reputation: 539735
Using NSPredicate
you can simplify your search a bit:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"en BEGINSWITH %@", searchText];
NSArray *tempSearch = [items filteredArrayUsingPredicate:predicate];
If you want case-insensitive search, replace BEGINSWITH
by BEGINSWITH[c]
.
See Using Predicates in the "Predicate Programming Guide" for more information.
Upvotes: 1
Reputation: 4235
Ok i've got something but isn't correctly in 100%.
for (NSDictionary *item in items) {
NSRange range = [[item objectForKey:@"en"] rangeOfString : searchText];
if (range.location != NSNotFound) {
NSLog(@"Found");
[tempSearch addObject:item];
}
}
When i type "e" i've got "some", "something", "else" - i think correctly will be when only "else" will be returned.
Ok i've got it.
if (range.location != NSNotFound && range.location == 0) {
Upvotes: 0