搜索栏不工作?

时间:2011-10-03 06:54:33

标签: iphone uitableview uisearchbar uisearchbardelegate

我有一个SQL文件,其中存储了5种不同类型的数据。我将这些数据添加到用键指定的字典中。然后我将这个字典添加到tableData数组作为table和searchBar的dataSource。但它没有搜索任何东西。

添加以下代码

- (void)viewDidLoad {
[super viewDidLoad];


dataSource =[[NSMutableArray alloc] init];
tableData = [[NSMutableArray alloc]init];
searchedData = [[NSMutableArray alloc]init];


NSString *query = [NSString stringWithFormat:@"SELECT * FROM Vegetables"];

SQLite *sqlObj1 = [[SQLite alloc] initWithSQLFile:@"ShoppersWorld.sqlite"];
[sqlObj1 openDb];
[sqlObj1 readDb:query];

    //  [query release];
for (int i=0; i<[dataSource count]; i++) {
    NSLog(@"data:%@",[dataSource objectAtIndex:i]);
}

while ([sqlObj1 hasNextRow]) 
{

    NSString *name=[sqlObj1 getColumn:1 type:@"text"];
    NSString *price=[sqlObj1 getColumn:2 type:@"text"];
    NSString *quantity=[sqlObj1 getColumn:3 type:@"text"];
    NSString *unit=[sqlObj1 getColumn:4 type:@"text"];
    NSString *total=[sqlObj1 getColumn:5 type:@"text"]; 


    dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys: name,@"nameOfVegetables",
                                                                price,@"priceOfVegetables",
                                                                quantity,@"quantityOfVegetables",
                                                                unit,@"unitOfVegetables",
                                                                total,@"totalPriceOfVegetables",nil];


        //NSLog(@"results:%@ %@",dict);
    [dataSource addObject:dict];


}

[tableData  addObjectsFromArray:dataSource];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];

}

    // Set up the cell...
    // Configure the cell.


else {

    cell.productLbl.text= [NSString stringWithFormat:@"%@",[[tableData objectAtIndex:indexPath.row]objectForKey:@"nameOfVegetables"] ];     
    cell.bPriceLbl.text = [NSString stringWithFormat:@"Rs %d/Kg",
                                        [[[tableData objectAtIndex:indexPath.row] objectForKey:@"priceOfVegetables"] intValue]]; 

    cell.qtyLbl.text = [NSString stringWithFormat:@"QTY: %@ %@",[[tableData objectAtIndex:indexPath.row] 
                                                               objectForKey:@"quantityOfVegetables"],[[tableData objectAtIndex:indexPath.row] objectForKey:@"unitOfVegetables"]] ;

    cell.tPriceLbl.text = [NSString stringWithFormat:@"TOTAL: %@",[[tableData objectAtIndex:indexPath.row]
                                                                    objectForKey:@"totalPriceOfVegetables"]];

}
return cell;
}

#pragma搜索操作

- (IBAction)search:(id)sender{

sBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0,40,320,30)];
sBar.delegate = self;
[self.view addSubview:sBar];

}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{

    // only show the status bar’s cancel button while in edit mode
[sBar setShowsCancelButton:YES animated:YES];
sBar.autocorrectionType = UITextAutocorrectionTypeNo;
    // flush the previous search content
[tableData removeAllObjects];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{

[sBar setShowsCancelButton:NO animated:YES];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{

    [tableData removeAllObjects];// remove all data that belongs to previous search
    if([searchText isEqualToString:@""] || searchText==nil){
        [tableview reloadData];
        return;

}
NSInteger counter = 0;
for(NSString *name in dataSource)

    for (int i = 0; i < [dataSource count]; i++)
    {
        NSMutableDictionary *temp = (NSMutableDictionary*) [dataSource objectAtIndex:i];
        NSString *name = [NSString stringWithFormat:@"%@", [temp valueForKey:@"nameOfVegetables"]];
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];      
        NSRange r = [name rangeOfString:searchText options:NSCaseInsensitiveSearch];        
        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];
    }

[tableview reloadData];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{

sBar.hidden= YES;
    // if a valid search was entered but the user wanted to cancel, bring back the main list content
[tableData removeAllObjects];
[tableData addObjectsFromArray:dataSource];
@try{
    [tableview reloadData];
}
@catch(NSException *e){
}
[sBar resignFirstResponder];
sBar.text = @"";
}

1 个答案:

答案 0 :(得分:0)

在搜索委托方法中,您不使用searchingData而是使用tableData数组进行操作。正如这些名称所示,array searchingData应该存储过滤后的数据
顺便说一下,你使用sqlite作为数据源并将所有数据库吸收到数组中的方法是错误的。在cellForRowAtIndexPath中,只从sqlite数据库中读取您当前需要的数据

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   // load from sqlite only data for this cell.
   // Use searchBar.text with sqlite's LIKE to filter data from database
   NSUInteger row = [indexPath row];
   static NSString *CellIdentifier = @"SignsCellIdentifier";
   UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:CellIdentifier];
   if (cell == nil) {                                       
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    NSString *sql = [NSString stringWithFormat:@"SELECT fieldNameFromTable FROM TableName WHERE FieldToLookForIn LIKE \"%%%@%%\" LIMIT 1 OFFSET %u", searchBar.text ? searchBar.text : @"", row];
    sqlite3_stmt *stmt;
    int res = sqlite3_prepare_v2(database, [sql UTF8String], -1, &stmt, NULL);
    if (res != SQLITE_OK) {
        NSLog(@"sqlite3_prepare_v2() failed"];
        return nil;
    }

    if (sqlite3_step(stmt) == SQLITE_ROW) {
        const unsigned char *name = sqlite3_column_text(stmt, 0);            
        cell.text = [NSString stringWithUTF8String:(const char*)name];
    }
    sqlite3_finalize(stmt);
return cell;
}


如何在这种方法中应用搜索?在textDidChange中什么也不做,只需调用[tableView reloadData]。并在cellForRowAtIndexPath中使用searchBar.text作为搜索词,使用sqlite LIKE加载数据。所以reloadData只会加载过滤后的记录。 searchBarSearchButtonClicked将只调用它的调用者的resignFirstResponder,删除键盘屏幕。它不需要再做任何事情,因为搜索已经完成。 searchBarCancelButtonClicked会将其调用者的text属性设置为nil,调用reload数据并再次调用resignFirstResponder。

- (void)searchBarCancelButtonClicked:(UISearchBar *)s {
    s.text = nil;
    [tableView reloadData];
    [s resignFirstResponder];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)s {
    // search is already done
    [s resignFirstResponder];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [tableView reloadData];
}

numberOfRowsInSection还应该使用与cellForRowAtIndexPath中相同的SELECT请求db,但使用SELECT COUNT。写这个方法将是你的功课)