我创建了一个带有三个标签的自定义UITableviewCell,并将值传递给每个标签。它现在工作正常。现在我想在我的应用程序中添加搜索栏来搜索所有标签。这是我的代码..
- (void)viewDidLoad {
[super viewDidLoad];
productArray=[[NSMutableArray alloc]init];
//Creating a temparay objects of Person
PersonDetail *personObj = [[PersonDetail alloc] init];
personObj.firstName = @"Adeem";
personObj.lastName = @"Basraa";
personObj.phoneNumber = @"123456789";
[productArray addObject:personObj];
[personObj release];
PersonDetail *personObj = [[PersonDetail alloc] init];
personObj.firstName = @"Ijaz";
personObj.lastName = @"Ahmed";
personObj.phoneNumber = @"987654321";
[productArray addObject:personObj];
[personObj release];
PersonDetail *personObj = [[PersonDetail alloc] init];
personObj.firstName = @"Waqas";
personObj.lastName = @"Noor";
personObj.phoneNumber = @"45656789";
[productArray addObject:personObj];
[personObj release];
searchData=[[NSMutableArray alloc]init];
[searchData addObjectsFromArray:productArray];
dataTable.delegate=self;
dataTable.dataSource=self;
[dataTable reloadData];
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
if ((bar.text !=nil)&&(![searchBar.text isEqualToString:@""])&&(bar.text.length>=3)) {
searchText=bar.text;
NSMutableArray *array=[[NSMutableArray alloc]init];
for (NSString *stemp in productArray ) {
NSRange titleResult=[stemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResult.length>0) {
[array addObject:stemp];
}
}
[bar setShowsCancelButton:YES];
[self.searchData removeAllObjects];
[self.searchData addObjectsFromArray:array];
[self.dataTable reloadData];
[array release];
}else {
[searchData removeAllObjects];
[searchData addObjectsFromArray:productArray];
[self.dataTable reloadData];
}
问题是当我开始在搜索栏中输入时,应用程序崩溃了。任何帮助将不胜感激。谢谢。
答案 0 :(得分:2)
希望这可能会对你有所帮助。
在.h文件中声明
NSMutableArray *array;
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText{
[copyListOfItems removeAllObjects];
if([searchText length] > 3) {
self.tableView.scrollEnabled = YES;
[self searchTableView];
}
else {
self.tableView.scrollEnabled = NO;
}
}
- (void) searchTableView {
array=[[NSMutableArray alloc]init];
NSString *searchText = searchBar.text;
for (NSString *sTemp in productArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[array addObject:sTemp];
}
[self.tableView reloadData];
}
我为其中的任何错误道歉。