Thread: Search Bar
View Single Post
  #3 (permalink)  
Old March 15th, 2012, 10:09 PM
Jule Jule is offline
Authorized User
Points: 62, Level: 1
Points: 62, Level: 1 Points: 62, Level: 1 Points: 62, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Mar 2011
Posts: 16
Thanks: 8
Thanked 0 Times in 0 Posts
Default thanks

I thought it would be easy like the tutorial in chapter 10 but I was wrong.

I have coded wrong, or not used the right coding for this.

tried other examples, including Apples Tutorial but got into a big mess.

this code has 3 errors and 1 warning.


any help would be appreciated. hate to abandon this after all the work put into it. It works without the search perfectly but I would like a search function as there are a lot of items in table.


Code:
//  RootViewController.h
//  TableViewApp
//
//  Created by OZTech 2012.
//  Copyright OZTech 2012. All rights reserved.
//

#import "cropLibraryDao.h"
#import "cropListingViewCell.h"

@interface RootViewController : UITableViewController 
<UISearchBarDelegate> {
    
	cropLibraryDao *dao;
	
    NSDictionary *cropTitles;
	NSArray *crops;
	
	IBOutlet cropListingViewCell *_cell;
	
	//---search---
    IBOutlet UISearchBar *searchBar;
    BOOL isSearchOn;
	BOOL canSelectRow;	
	NSMutableArray *listOfCrops;
	NSMutableArray *searchResult;
	
	
}

@property (nonatomic, retain) NSDictionary *cropTitles;
@property (nonatomic, retain) NSArray *crops;



//---search---
@property (nonatomic, retain) UISearchBar *searchBar; 
- (void) doneSearching: (id)sender;
- (void) searchCropTableView;




@end


Code:
//  RootViewController.m
//  TableViewApp
//
//  Created by OZTech 2012.
//  Copyright OZTech 2012. All rights reserved.
//

#import "RootViewController.h"
#import "DetailViewController.h"

@implementation RootViewController

@synthesize cropTitles, crops;
@synthesize searchBar;


#define CELL_HEIGHT 80.0

- (void)viewDidLoad {
	
	// path to the propery list file
	
	NSString *path = [[NSBundle mainBundle] pathForResource:@"TestData" ofType:@"plist"];
	
	// load the list into the dictionary
	NSDictionary *dic = [[NSDictionary alloc] initWithContentsOfFile:path];
	
	// save the dictionary object to the property
	self.cropTitles = dic;
	
	NSArray *array = [[cropTitles allKeys] sortedArrayUsingSelector:@selector(compare:)];
	self.crops = array;
	
	
	
	[dic release];
	
	//---search---
	
	//---display the searchbar---
	self.tableView.tableHeaderView = searchBar;
	searchBar.autocorrectionType = UITextAutocorrectionTypeYes;
	
	//---copy all the crop names in the dictionary into the listOfCrops array---
	listOfCrops = [[NSMutableArray alloc] init];
	for (NSString *crop in array) 
	{
   	    NSArray *crops = [cropTitles objectForKey:crop];
		for (NSString *title in crops)
		{
			[listOfCrops addObject:title];
		}
	}
	
	//---used for storing the search result---
	searchResult = [[NSMutableArray alloc] init];
	
	isSearchOn = NO;
	canSelectRow = YES;
	
	
	[super viewDidLoad];
}	
	//---fired when the user taps on the searchbar---
	- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
		isSearchOn = YES;
		canSelectRow = NO;
		self.tableView.scrollEnabled = NO;
		//---add the Done button at the top---
		self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
												   initWithBarButtonSystemItem:UIBarButtonSystemItemDone
												   target:self action:@selector(doneSearching:)] autorelease];
	}
	
	//---done with the searching---
	- (void) doneSearching:(id)sender {
		isSearchOn = NO;
		canSelectRow = YES;
		self.tableView.scrollEnabled = YES;
		self.navigationItem.rightBarButtonItem = nil;
		
		//---hides the keyboard---
		[searchBar resignFirstResponder];
		//---refresh the TableView---
		[self.tableView reloadData];
	}
	
	//---fired when the user types something into the searchbar---
	- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
		//[searchResult removeAllObjects]
		//---if there is something to search for---
		if ([searchText length] > 0) {
			isSearchOn = YES;
			canSelectRow = YES;
			self.tableView.scrollEnabled = YES;
			[self searchCropTableView];
		}
		else {		
			//---nothing to search---
			isSearchOn = NO;
			canSelectRow = NO;
			self.tableView.scrollEnabled = NO;
		}	
		[self.tableView reloadData];
	}
	
	//---performs the searching using the array of crops---
	- (void) searchCropTableView {
		//---clears the search result---
		[searchResult removeAllObjects];
		
		for (NSString *str in listOfCrops)
		{
			NSRange titleResultsRange = [str rangeOfString:searchBar.text options:NSCaseInsensitiveSearch];
			if (titleResultsRange.length > 0) 
				[searchResult addObject:str];
		}
	}
	
	//---fired when the user taps the Search button on the keyboard---
	- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
		[self searchCropTableView];
	}
	
//-------
- (void)viewWillAppear:(BOOL)animated {
    dao = [[cropLibraryDao alloc] initWithLibraryName:@"TestData"];
    self.title = @"Crop List";
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/


 // Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations.
	return YES; //(interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release anything that can be recreated in viewDidLoad or on demand.
	// e.g. self.myOutlet = nil;
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (isSearchOn)
		return 1;
	else
		return [crops count];
	
	
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (isSearchOn) {
		return [searchResult count];
	} else
	{
		return [dao libraryCount];
	}
}

// Customize the appearance of table view cells.

	/*
	- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
	static NSString *CellIdentifier = @"LibraryListingCell";
	    
    cropListingViewCell *cell = (cropListingViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"cropListingView" owner:self options:nil];
        cell = [_cell autorelease];
        _cell = nil;
    }
*/
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
		
		static NSString *CellIdentifier = @"Cell";
		
		UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
		if (cell == nil) {
			cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
		}
		
	if (isSearchOn) {		
		NSString *cellValue = [searchResult objectAtIndex:indexPath.row];
		cell.textLabel.text = cellValue;		
	} else 
		
		
	
	cell.nameLabel.text = [[dao libraryItemAtIndex:indexPath.row] valueForKey:@"name"];    
    cell.levelLabel.text = [NSString stringWithFormat:@"Level %@ ", 
                                    [[dao libraryItemAtIndex:indexPath.row] valueForKey:@"level"]];
    cell.cropImageView.image = [UIImage 
                                 imageNamed:[[dao libraryItemAtIndex:indexPath.row] valueForKey:@"cropImage"]];

	
	
    return cell;
}



// Override to support row selection in the table view.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DetailViewController *controller = [[DetailViewController alloc] 
                                        initWithcropData:[dao libraryItemAtIndex:indexPath.row]
                                        nibName:@"DetailViewController" bundle:[NSBundle mainBundle]];
    controller.title = [[dao libraryItemAtIndex:indexPath.row] valueForKey:@"name"];
    [self.navigationController pushViewController:controller animated:YES];
    [controller release];    
}

	
	
	

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return CELL_HEIGHT;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


- (void)dealloc {
	[crops release];
	[cropTitles release];
	[searchBar release];
    [super dealloc];
}


@end

thanks.