The SearchPredicate.h
// SearchPredicate.h
//
// Created by Yasir Ibrahim on 24/12/08.
#import <UIKit/UIKit.h>
@interface SearchPredicate : NSObject {
NSString* searchTerm;
}
@property (nonatomic, retain) NSString* searchTerm;
- (BOOL)evaluateWithObject:(id)object;
@end
And the SearchPredicate.m
// SearchPredicate.m
// Created by Yasir Ibrahim on 24/12/08.
#import "SearchPredicate.h"
@implementation SearchPredicate
@synthesize searchTerm;
- (BOOL)evaluateWithObject:(id)object
{
searchTerm = [searchTerm stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if([searchTerm compare:@"*"] == 0 || [searchTerm compare:@""] == 0)
{
return TRUE;
}
NSString* name = [object objectForKey:@"Name"];
if([name length] >= [searchTerm length])
{
NSRange r;
r.length = [searchTerm length];
r.location = 0;
if([name rangeOfString:searchTerm options:NSCaseInsensitiveSearch range:r].location != NSNotFound)
{
return TRUE;
}
else
{
return FALSE;
}
}
else
{
return FALSE;
}
}
@end
And here is how to use it with UISearchBar:
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[mySearchBar resignFirstResponder];
SearchPredicate* sp = [[SearchPredicate alloc] init];
sp.searchTerm = [mySearchBar text];
[pickerItemFilteredList release];
//pickerItemFilteredList = [pickerItemList filteredArrayUsingPredicate:sp];
pickerItemFilteredList = [[NSMutableArray alloc] init];
for(int i=0; i<[pickerItemList count]; i++)
{
if([sp evaluateWithObject:[pickerItemList objectAtIndex:i]])
{
[pickerItemFilteredList addObject:[pickerItemList objectAtIndex:i]];
}
}
[pickerItemFilteredList retain];
[myPickerView reloadComponent:0];
if([pickerItemFilteredList count] == 1)
{
[self showStoreOnMapAtRow:0];
}
}
Notice that I was using NSPredicate (sp) with filteredArrayUsingPredicate method of NSMuteableArray before. However as I have not implemented that method for our new class yet (you can do this, I guess using categories etc., and post back in comments) I have commented it and using a for loop and evaluateWithObject on each object of NSMuteableArray to have the same effect.