0

У меня есть класс ViewController с соответствующим .XIB-файлом. Вот код ViewController:UITableViewController с UISearchDisplayController не перезагружает данные

ViewController.h:

#import <UIKit/UIKit.h> 
#import <Foundation/Foundation.h> 

@interface ViewController : UIViewController 
{  
    NSArray *news; 
    NSMutableData *data; 
} 

@property (strong, nonatomic) IBOutlet UITableView *mainTableView; 
@property (strong, nonatomic) IBOutlet UISearchBar *searchBar; 

@property (strong, nonatomic) Results *result; 

@end 

ViewController.m:

#import "ViewController.h" 
#import "Results.h" 

@interface ViewController() 

@end 

@implementation ViewController 

@synthesize result, mainTableView, searchBar; 

-(id) init 
{ 
    self = [super initWithNibName:@"ViewController_iPhone" bundle:nil]; 

    if (self) 
    { 
     result = [[Results alloc] init]; 
     mainTableView = [[UITableView alloc] init]; 
     [self.mainTableView setDelegate:self]; 
    } 

    return self; 
} 

- (void)viewDidLoad 
{ 
    self.title = @"Search"; 
    [[UINavigationBar appearance] setTintColor:[UIColor blackColor]]; 

    [super viewDidLoad]; 
} 

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar 
{ 
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; 
    NSString *query = searchBar.text; 
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://samplesite.com/external/metasearchjson.php?query=%@", query]]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
    [NSURLConnection connectionWithRequest:request delegate:self]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    data = [[NSMutableData alloc] init]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData 
{ 
    [data appendData:theData]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 
    NSArray *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:NULL]; 

    if ([responseDict isKindOfClass:[NSArray class]]) { 
     news = responseDict; 
     //[mainTableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade]; 
     [[self mainTableView] reloadData]; 
     NSLog(@"%@", mainTableView); 
    } else { 
     NSLog(@"JSON Error."); 
    } 
} 

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:[indexPath row] inSection:0]]; 
    NSString *url = _getString([[news objectAtIndex:[indexPath row]] objectForKey:@"link"]); 
    [result getURL:url]; 
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; 
    [self.navigationController pushViewController:result animated:YES]; 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"The download could not complete - please make sure you're connected to either 3G or Wi-Fi." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil]; 
    [errorView show]; 
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 
} 

- (int)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; 
} 

- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [news count]; 
} 

NSString *_getString(id obj) 
{ 
    return [obj isKindOfClass:[NSString class]] ? obj : nil; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"]; 

    if(cell == nil){ 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MainCell"]; 
    } 

    cell.detailTextLabel.text = _getString([[news objectAtIndex:indexPath.row] objectForKey:@"metaScore"]); 
    cell.textLabel.text = _getString([[news objectAtIndex:indexPath.row] objectForKey:@"title"]); 

    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator]; 

    return cell; 
} 

Мои соединения все работают, а код успешно помещает JSON данных в UITableView.

Моя проблема в том, что табличный вид не перезагружается!

Я попытался просто загрузить его без UISearchDisplayController, и он отлично работает. Я думаю, что это что-то вроде переопределения. Где мой TableView перезагружает данные, это просто не работает. То, что также странно, заключается в том, что если вы набираете что-то на экран поиска, отображается представление таблицы. Что я делаю неправильно, что панель поиска не перезагружает данные?

+0

Если вы используете контроллер отображения поиска, вам, вероятно, необходимо перезагрузить таблицу результатов поиска: '[self.searchDisplayController.searchResultsTableView reloadData]'. –

+0

Посмотрите мои комментарии на первый ответ. –

ответ

0

В поисковом отображении делегата, вам нужно реализовать

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString 

и вернуть YES.

+0

Нет, не работает. Я добавил это в файл 'ViewController.m'; Я предполагаю, что это то, что вы хотели? –

+0

Почему он не работал, как вы думаете? –

0

Попробуйте сделать следующие шаги:

В ViewController.h:

добавить протоколы:

@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> 

добавить свойство:

@property (strong, nonatomic) NSArray* news; 

затем заменить в connectionDidFinishLoading: метод новости = responseDict; а

self.news = responseDict; 

затем выполнить reloadData в главном потоке:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
... 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     [[self mainTableView] reloadData]; 
    }); 

в линии вставки ViewController.m [self.mainTableView setDataSource: самостоятельная]; :

-(id) init 
{ 
    self = [super initWithNibName:@"ViewController_iPhone" bundle:nil]; 

    if (self) 
    { 
... 
     [self.mainTableView setDelegate:self]; 
     [self.mainTableView setDataSource: self]; 
    } 

    return self; 
} 

надеюсь, что это вам поможет.

+0

Нет, не работает. –

+0

Почему он не работал, как вы думаете? –

+0

@ Witch-King обновил мой ответ – stosha

Смежные вопросы