开发者

IOS: searchbar in tableview

I am creating a searchbar in a tableview but I have problems with this method delegate because I fill the table view with array inside another array...I show my code:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
ProgramAppDelegate *appDelegate = (ProgramAppDelegate *)[[UIApplication sharedApplication] delegate];
[tableData removeAllObjects];// remove all data that belongs to previous search
if([searchText isEqualToString:@""] || searchText==nil){
    [myTableView reloadData];
    return;
}
NSInteger counte开发者_如何学Gor = 0;
for(NSString *name in appDelegate.globalArray )
{
    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];
}

You can see the code "for(NSString *name in appDelegate.globalArray )" it don't work because I fill the table view with elements of arrays inside this global array, I make an example

In a row of my table view there is a uitableviewcell and inside it there are four label; I write these label with string of this globalArray but in this way:

[cell.label1 setText:[[appDelegate.globalArray objectAtIndex:indexPath.row]objectAtIndex:1]];
[cell.label2 setText:[[appDelegate.globalArray objectAtIndex:indexPath.row]objectAtIndex:2]];
[cell.label3 setText:[[appDelegate.globalArray objectAtIndex:indexPath.row]objectAtIndex:3]];
[cell.label4 setText:[[appDelegate.globalArray objectAtIndex:indexPath.row]objectAtIndex:4]];

then in delegate method for searchbar the code "for(NSString *name in appDelegate.globalArray )" don't work, How can I change my code?

** I DON'T SAY THAT I WANT TO CHECK ONLY LABEL1 FOR THE SEARCH


The problem here is that globalArray is an array of arrays. So the loop should be something like.

for(NSArray *rowArray in appDelegate.globalArray )
{
    for ( NSString *name in rowArray ) {
        // Do your processing here..
    }
}

Using tableData

In your tableView:cellForRowAtIndexPath:, do this

[cell.label1 setText:[[tableData objectAtIndex:indexPath.row]objectAtIndex:1]];
[cell.label2 setText:[[tableData objectAtIndex:indexPath.row]objectAtIndex:2]];
[cell.label3 setText:[[tableData objectAtIndex:indexPath.row]objectAtIndex:3]];
[cell.label4 setText:[[tableData objectAtIndex:indexPath.row]objectAtIndex:4]];

In your numberOfSectionsInTableView:, return 1;

In your tableView:numberOfRowsInSection:, return [tableData count];

You should include a method that will reset the search data to the original content when the user stops searching.

- (void)resetSearchData {
    // Get appDelegate first.

    self.tableData = [NSArray arrayWithArray:appDelegate.globalArray];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜