搜索结果未显示

时间:2015-03-17 12:03:11

标签: ios uitableview uisearchbar

我是iOS开发的新手。在我的项目中,我采用了tableView和搜索栏。现在,当我搜索我的tableview的一个数据时,没有搜索结果。任何人都可以解决我的问题吗?

任何帮助将不胜感激。提前谢谢。

这是我的ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property(strong, nonatomic) NSMutableData *postData;
@property(nonatomic, strong)NSArray *arrDetail;
@property(nonatomic, strong)NSArray *searchResults;
@property (weak, nonatomic) IBOutlet UITableView *parserTable;
@property (strong, nonatomic) IBOutlet UIActivityIndicatorView *mySpinner;


@end

这是我的ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
_mySpinner.hidden = NO;


[self fetchData];

// Do any additional setup after loading the view, typically from a nib.

}

- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}


- (BOOL)prefersStatusBarHidden {
return YES;
}


- (void) fetchData {

 [_mySpinner startAnimating];

NSString *post = [NSString stringWithFormat:@"test=Message&this=isNotReal"];
_postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [_postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://svn.indusnettechnologies.com/HHC/webservice/users/countrylist?apiKey=hgfyhfyi87hgc67"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:_postData];

NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];

NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
NSLog(@"requestReply: %@", requestReply);
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) {
    _postData = [NSMutableData data];
}
else{
    //error
}

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[_postData appendData:data];

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

// The request is complete and data has been received
// You can parse the stuff in your instance variable now
// self.data parse

NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:self.postData options:kNilOptions error:nil];
self.arrDetail = [dict valueForKey:@"Countries"];

[self.mySpinner stopAnimating];
self.mySpinner.hidden = YES;

[self.parserTable reloadData];

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// The request has failed for some reason!
// Check the error var

}

#pragma mark Table View Delegates


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableCell"];

UILabel *lbl1 = (UILabel*)[cell.contentView viewWithTag:2];
lbl1.text = [[self.arrDetail objectAtIndex:indexPath.row]valueForKey:@"CountryCode"];

UILabel *lbl2 = (UILabel*)[cell.contentView viewWithTag:1];
lbl2.text = [[self.arrDetail objectAtIndex:indexPath.row]valueForKey:@"CountryName"];

UILabel *lbl3 = (UILabel*)[cell.contentView viewWithTag:3];
lbl3.text = [NSString stringWithFormat:@"%d.", indexPath.row];


return cell;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

//return [self.arrDetail count];

if (tableView == self.searchDisplayController.searchResultsTableView) {
    return [_searchResults count];

} else {
    return [_arrDetail count];

}

}

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate
                                predicateWithFormat:@"SELF contains[cd] %@",
                                searchText];

_searchResults = [_arrDetail filteredArrayUsingPredicate:resultPredicate];
}

#pragma mark - UISearchDisplayController delegate methods


-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
                           scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                  objectAtIndex:[self.searchDisplayController.searchBar
                                                 selectedScopeButtonIndex]]];


return YES;
}


- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

1 个答案:

答案 0 :(得分:0)

像我一样改变以下方法:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableCell"];

if (cell == nil)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSMutableDictionary * tempDict;

if (tableView == self.searchDisplayController.searchResultsTableView) 
{
    tempDict = [_searchResults objectAtIndex:indexPath.row];
}
else 
{
    tempDict = [_arrDetail objectAtIndex:indexPath.row];
}

UILabel *lbl1 = (UILabel*)[cell.contentView viewWithTag:2];
lbl1.text = [tempDict valueForKey:@"CountryCode"];

UILabel *lbl2 = (UILabel*)[cell.contentView viewWithTag:1];
lbl2.text = [tempDict valueForKey:@"CountryName"];

UILabel *lbl3 = (UILabel*)[cell.contentView viewWithTag:3];
lbl3.text = [NSString stringWithFormat:@"%d.", indexPath.row];


return cell;

}

您的谓词中也存在问题。改变它

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    //country_name and country_code are keys in your dictionary of country
    NSPredicate *p1 = [NSPredicate predicateWithFormat:@"country_name contains[cd] %@", searchText];
    NSPredicate *p2 = [NSPredicate predicateWithFormat:@"country_code contains[cd] %@", searchText];

    NSPredicate *resultPredicate = [NSCompoundPredicate orPredicateWithSubpredicates: @[p1, p2]];

    _searchResults = [_arrDetail filteredArrayUsingPredicate:resultPredicate];

}