搜索栏取消按钮不重新加载原始表视图和数据

时间:2016-04-05 23:01:05

标签: ios objective-c uisearchbar uisearchcontroller

搜索和其他一切正常,除非我在搜索栏上单击“取消”时,会出现一个空白屏幕,其上显示空白搜索栏和原始表格视图的导航栏。 Core Data中原始未过滤的数组不会重新加载。我已经检查了"显示取消按钮"在故事板中。我研究了很多帖子和文章,但没有任何建议有效。控制台消息显示按下取消按钮后,我在其他消息中看到"获取后的事件:"执行两次。第二个(最后一次)它包含了我所有的托管对象/事件,但随后"过滤了数组:"是空白的,"事件:"是空白的," events.self.count:" = 0,searchBarText为空,self.events.count = 0。

EventViewController.h文件:

    #import <UIKit/UIKit.h>

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

    @interface EventViewController: UITableViewController       <UISearchResultsUpdating, UISearchControllerDelegate, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>


    {
        IBOutlet UISearchBar *searchBar;
    }

        @end

EventViewController.m文件:

#import "EventViewController.h"
#import <CoreData/CoreData.h>
#import "EventDetailViewController.h"

@interface EventViewController ()    

@property (nonatomic, strong) NSMutableArray *events;
@property (nonatomic, strong) UISearchController *searchController;
@property(nonatomic, weak) id< UISearchResultsUpdating > searchResultsUpdater;
@property (nonatomic,strong) UISearchBar *_searchBar;
@property(nonatomic, assign) BOOL obscuresBackgroundDuringPresentation;
@property(nonatomic, weak) id< UISearchControllerDelegate > delegate;

//@property(nonatomic, assign, getter=isActive) BOOL active;

@end


@implementation EventViewController
NSMutableArray *events;


- (NSManagedObjectContext *)managedObjectContext {

    NSLog(@"Setting up managed object context");

    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate performSelector:@selector(managedObjectContext)]) {
        context = [delegate managedObjectContext];
    }
    return context;

}



- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{

    // Fetch the events from persistent data store

    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
   NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Event"];

    self.events = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];


      NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", self.searchController.searchBar.text];

   self.events = [[self.events filteredArrayUsingPredicate:resultPredicate] mutableCopy];


 }


- (BOOL)shouldReloadTableForSearchString:(UISearchController *)searchController


{


    return YES;

 }



- (void)viewDidLoad {
    [super viewDidLoad];

    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    self.searchController.dimsBackgroundDuringPresentation = false;
    self.tableView.tableHeaderView = self.searchController.searchBar;
    self.definesPresentationContext = true;
    self.searchController.searchBar.delegate = self;
    self.searchController.delegate = self;
    self.searchController.obscuresBackgroundDuringPresentation = NO;

}



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

    [self.searchController.searchBar becomeFirstResponder];
}




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



- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    // Fetch the events from persistent data store
    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Event"];
    self.events = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];

    [self.tableView reloadData];
}




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

    self.searchController.searchBar.text = nil;
    [self.searchController.searchBar resignFirstResponder];
    [self.tableView reloadData];       

    }


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {


    return 1;
}



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


    {

        return [self.events count];
    }
}



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


    static NSString *CellIdentifier = @"Cell";
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];


    // Configure the cell...
    NSManagedObject *event = [self.events objectAtIndex:indexPath.row];
    [cell.textLabel setText:[NSString stringWithFormat:@"%@", [event valueForKey:@"name"]]];

        {

        event = [events objectAtIndex:indexPath.row];
        NSManagedObject *event = [self.events objectAtIndex:indexPath.row];
        [cell.textLabel setText:[NSString stringWithFormat:@"%@", [event valueForKey:@"name"]]];
    }

    return cell;

}



// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}



// Override to support editing the table view.

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSManagedObjectContext *context = [self managedObjectContext];

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete object from database
        [context deleteObject:[self.events objectAtIndex:indexPath.row]];

        NSError *error = nil;
        if (![context save:&error]) {
            NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]);
            return;
        }

        // Remove event from table view
        [self.events removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}


#pragma mark - Navigation


// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)send


{

    if ([[segue identifier] isEqualToString:@"UpdateEvent"]) {
        NSManagedObject *selectedEvent = [self.events objectAtIndex:[[self.tableView indexPathForSelectedRow] row]];

        EventDetailViewController *destViewController = segue.destinationViewController;
        destViewController.event = selectedEvent;
    }
}

@end

2 个答案:

答案 0 :(得分:1)

如果你正在调用取消函数,你不应该过滤数组,所以你不应该执行我下面提到的行,为此你可以检查self.searchController.searchBar.text的长度,或者你可以设置一个布尔值检查是否单击了取消或在文本字段中输入了文本

  NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", self.searchController.searchBar.text];

  self.events = [[self.events filteredArrayUsingPredicate:resultPredicate] mutableCopy];

答案 1 :(得分:0)

在你的searchBarCancelButtonClicked中添加self.searchController.active = NO; 在reloadData之前

在代码中创建搜索控制器,不要删除故事板中的任何搜索控件

在.h

中添加UISearchBarDelegate

添加属性

@property (strong, nonatomic) UISearchController *searchController;

在viewDidLoad

self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.dimsBackgroundDuringPresentation = NO;
self.searchController.searchBar.delegate = self;

self.tableView.tableHeaderView = self.searchController.searchBar;
self.definesPresentationContext = YES;
[self.searchController.searchBar sizeToFit];