@interface MySearchScreenAppViewController : UIViewController
UITableView *myTableView;
NSMutableArray *dataSource; //will be storing all the data
NSMutableArray *tableData;//will be storing data that will be displayed in table
NSMutableArray *searchedData;//will be storing data matching with the search string
UISearchBar *sBar;//search bar
}
@property(nonatomic,retain)NSMutableArray *dataSource;
@end
- (void)loadView {
[super loadView];
sBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0,0,320,30)];
sBar.delegate = self;
[self.view addSubview:sBar];
myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 31, 300, 400)];
myTableView.delegate = self;
myTableView.dataSource = self;
[self.view addSubview:myTableView];
//initialize the two arrays; dataSource will be initialized and populated by appDelegate
searchedData = [[NSMutableArray alloc]init];
tableData = [[NSMutableArray alloc]init];
[tableData addObjectsFromArray:dataSource];//on launch it should display all the records
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//NSLog(@"contacts error in num of row");
return [tableData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = @"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
}
cell.text = [tableData objectAtIndex:indexPath.row];
return cell;
}
#pragma mark UISearchBarDelegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
// only show the status bar's cancel button while in edit mode
sBar.showsCancelButton = YES;
sBar.autocorrectionType = UITextAutocorrectionTypeNo;
// flush the previous search content
[tableData removeAllObjects];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
sBar.showsCancelButton = NO;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
[tableData removeAllObjects];// remove all data that belongs to previous search
if([searchText isEqualToString:@""]||searchText==nil){
[myTableView reloadData];
return;
}
NSInteger counter = 0;
for(NSString *name in dataSource)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
NSRange r = [name rangeOfString:searchText];
if(r.location != NSNotFound)
{
if(r.location== 0)//that is we are checking only the start of the names.
{
[tableData addObject:name];
}
}
counter++;
[pool release];
}
[myTableView reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
// if a valid search was entered but the user wanted to cancel, bring back the main list content
[tableData removeAllObjects];
[tableData addObjectsFromArray:dataSource];
@try{
[myTableView reloadData];
}
@catch(NSException *e){
}
[sBar resignFirstResponder];
sBar.text = @"";
}
// called when Search (in our case "Done") button pressed
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder];
}
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after app launch
viewController.dataSource = [[NSMutableArray alloc]init];
for(char c = 'A';c<='Z';c++)
[viewController.dataSource addObject:[NSString stringWithFormat:@"%cTestString",c]];
UINavigationController *nvc = [[UINavigationController alloc]initWithRootViewController:viewController];
viewController.title = @"Search";
[window addSubview:nvc.view];
[window makeKeyAndVisible];
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
[tableData removeAllObjects];// remove all data that belongs to previous search
if([searchText isEqualToString:@""]||searchText==nil){
[myTableView reloadData];
return;
}
NSInteger counter = 0;
for(NSString *name in dataSource)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
NSRange r = [name rangeOfString:searchText];
if(r.location != NSNotFound)
[tableData addObject:name];
counter++;
[pool release];
}
[myTableView reloadData];
}
Do you have xcode project code for this?
ReplyDeleteamm..i will have to find...will upload it on monday
ReplyDeleteGreat Tutorial... Thank you very much.
ReplyDeleteFor some reason, though.. I can't get the data to load into the table when the app is initialized. It only loads after I hit the cancel button on the search bar. the [tableData addObjectsFromArray:dataSource] in the loadview method seems like it should do the trick right?
Anybody have any ideas?
Ved ... Can u please upload the code ??
ReplyDeleteI would love the source code for this tutorial. Thanks!
ReplyDeletethe style in your blog is sadly nearly unreadable. anyway thx for this blog-entry.
ReplyDeletevery gud... i like it... son...
ReplyDeleteHi,
ReplyDeleteI get two errors with my viewController, (viewController.dataSource...). Here is the message : error 'ViewController' undeclared (first use in function).
Why this problem ?
Thanks
Hi, sorry for the late reply, I have been bzzy with other tasks.
ReplyDeleteA lot many things have changed in 3.0/3.1
Please check if in the .h file viewController is injected by default or not. If it is something else, use the same name.
Could you please explain why you're using NSAutoreleasePool here?
ReplyDeleteI don think there is much need of autorelease pool there, but at the same time its harmless and can be helpful too.When the database is huge like in crm applications, the for loop might iterate large number of times and we are crating NSRange auto release objects for every iteration, so a new pool will ensure these objects are released immediatly after every iteration rather than stacking all the objects untill for loop ends and release them in next pool.
ReplyDeleteAlthough I am not sure removing the pool from there and testing it with huge database will cause any problems or not but atleast it gives certainity and assurance :)
How do I have the searchbar hidden underneath the navbar when it first comes up?
ReplyDeleteyou can try removing it from the view and add when required.
ReplyDeleteYou can also try changing the alpha value to 0.
How do i do it if my source of data is from a plist file?can anyone help?
ReplyDeleteI already have a text related app on iTunes. One thing it lacks is a search feature.
ReplyDeleteI need help. I am a novice to developing. Someone developed it for me and wants to charge an arm and a leg for this feature.
If you know anyone will to takes this task for a reasonable price I would appreciate it. Already spent a lot to develop the app. It NOW NEEDS A SEARCH FEATURE TO SEARCH WITHIN THE APP.
Thanks
@Learner, I am really short of time these days but send over your use case n ll try helping.
ReplyDeleteI received an error " class does not implement the UISearchBarDelegate/UITableViewDelegate " in MySearchScreenAppViewController until I added " to the MySearchScreenAppViewController.h file like so
ReplyDeleteexample:
@interface MySearchScreenAppViewController : UIViewController
{....
This blog does not show code within greater/less than signs.. here are the delegate protocols I added to the MySearchScreenAppViewController.h header file
ReplyDeleteUISearchBarDelegate, UITableViewDelegate, UITableViewDataSource
@above: well thanks for mentioning, ll check wat is the issue
ReplyDeleteGreat post!
ReplyDeletethx, thimon
wow, this code is full of bugs and the author don’t care for fixing them.
ReplyDeleteAmazing! If you were lazy to create a decent post you shouldn’t.
@above: I ll suggest u to quit iPhone dev bt thas upto u :P
ReplyDeletereally its very good one. thanks for sharing.iphone application development
ReplyDeleteHow do we make the search bar float and not scroll with the table view?
ReplyDeleteone way is to add searchBar as a separate subview.
ReplyDeleteso u have a view..on which u add a searchbar as subview say 40px tall and den add your tableview with top offset of 40px
Interesting post!!!! Thanks for sharing code for creating search bar. I am also an iphone application developer. I will try your code to create search bar.
ReplyDeleteiPhone Application Development
Well exposure of the application. When your apps get in the store, Apple will decide weather it will stay there or not.
ReplyDeleteiphone developer
Hi
ReplyDeleteDoes anyone know how to parse it with XML and make the data from the XML load in the searchbar?
Thanks,
Aaron
i copy and paste your data into my application but it is not working.... i don't know why....please specify good data.....
ReplyDeleteTo compare case insensitive, change the line to:
ReplyDeleteNSRange r = [name rangeOfString:searchText options:NSCaseInsensitiveSearch];
Very usefull code, it differs from others that is all programatically made.