如何添加核心数据的搜索栏

时间:2015-08-29 13:04:29

标签: ios

我已经尝试了stackoverflow的所有解决方案。但没有用... 我有一个名为“Notes”的实体。 我需要添加搜索栏来搜索我的表视图中的东西...

@interface ViewController ()

{
    NSDateFormatter *formatter;
    BOOL isChecked;   
     NSArray *searchResults;
}

@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UISearchDisplayController *searchController;

@property (nonatomic) BOOL *isChecked;

@property (strong) NSMutableArray *notes;

@end


@implementation ViewController

@synthesize tableView;

@synthesize addButton;

@synthesize managedObjectContext;

- (NSManagedObjectContext *)managedObjectContext {

    NSManagedObjectContext *context = nil;

    id delegate = [[UIApplication sharedApplication] delegate];

    if ([delegate performSelector:@selector(managedObjectContext)]) {

        context = [delegate managedObjectContext];

    }

    return context;

}

- (void)viewDidLoad {

    [super viewDidLoad];

    self.navigationItem.title = @"My Notes";
    tableView.dataSource = self;

    tableView.delegate = self;

    [self.view addSubview:tableView];

    formatter = [[NSDateFormatter alloc] init];

    formatter.doesRelativeDateFormatting = YES;

    formatter.locale = [NSLocale currentLocale];

    formatter.dateStyle = NSDateFormatterShortStyle;

    formatter.timeStyle = NSDateFormatterNoStyle;

         CATransition *animation = [CATransition animation];

            [animation setDuration:2.0];

            [animation setType:kCATransitionPush];

        [animation setSubtype:kCATransitionFromTop];

        [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];

        [[addButton layer] addAnimation:animation forKey:@"SwitchToDown"];

    // place search bar coordinates where the navbar is position - offset by statusbar

    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 20, 320, 44)];


    UIBarButtonItem *searchButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(toggleSearch)];

    self.navigationItem.rightBarButtonItem = searchButton;

    self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];

    self.searchController.searchResultsDataSource = self;

    self.searchController.searchResultsDelegate = self;

    self.searchController.delegate = self;

}

- (void)viewDidAppear:(BOOL)animated

{
    [super viewDidAppear:animated];

    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Notes"];

    NSError *error = nil;

    self.notes = [[managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy];

    NSSortDescriptor *titleSorter= [[NSSortDescriptor alloc] initWithKey:@"mod_time" ascending:NO];

    [self.notes sortUsingDescriptors:[NSArray arrayWithObject:titleSorter]];

    NSLog(@"Your Error - %@",error.description);

    [tableView reloadData];

}

#pragma mark - Search controller

- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
}

- (void) searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller

{
   // reposition the table where we want after search has completed

    // need to reschedule on runloop to rejig the table layout and correct the

    // offset and insets given no search bar will be displayed at the top of the controller

//    // as we remove it

//    dispatch_async(dispatch_get_main_queue(), ^{

//        self.tableView.contentInset = UIEdgeInsetsMake([self.topLayoutGuide length], 0, 0, 0);

//        self.tableView.contentOffset = CGPointMake(0, -[self.topLayoutGuide length]);

//    });

}

- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller
{

//    [self.searchBar removeFromSuperview];

}

- (void)toggleSearch{

    [self.view addSubview:self.searchBar];

    [self.searchController setActive:YES animated:YES];

    [self.searchBar becomeFirstResponder];

}

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];



    NSEntityDescription *entity = [NSEntityDescription

                                   entityForName:@"Notes" inManagedObjectContext:_notes];

    [fetchRequest setEntity:entity];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"notes.title contains[c] %@", searchText];

    [fetchRequest setPredicate:predicate];

    NSError *error;

    NSArray* searchResults = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString

                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]

                                      objectAtIndex:[self.searchDisplayController.searchBar

                                                     selectedScopeButtonIndex]]];

    return YES;

}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    // Return the number of sections.

    return searchResults.count;

}

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

{

    if (tableView == self.searchDisplayController.searchResultsTableView) {

        return [searchResults count];    

    } else {

      return self.notes.count;

}

}

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

{

    TableViewCell *cell = (TableViewCell*)[aTableView dequeueReusableCellWithIdentifier:@"MycellIdentifier"];
    if(cell == nil)

    {
        cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MycellIdentifier"];
    }

       // Configure the cell...

    NSManagedObject *note = [self.notes objectAtIndex:indexPath.row];

    NSDate *date = [note valueForKey:@"mod_time"];

    NSString *dateString = [formatter stringFromDate:date];

    cell.textLabel.text = [note valueForKey:@"title"];

    cell.detailTextLabel.text = dateString;

     cell.selectionStyle = UITableViewCellSelectionStyleNone;

     // cell.accessoryType = UITableViewCellAccessoryCheckmark;

    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(5, 5, 40, 40)];

    [button addTarget:self action:@selector(checkBoxClicked:) forControlEvents:UIControlEventTouchUpInside];

    [button setImage:[UIImage imageNamed:@"uncheck.png"] forState:UIControlStateNormal];

    [cell addSubview:button];

    [cell setIndentationLevel:1];

    [cell setIndentationWidth:45];

    return cell;
}

- (IBAction)addButtonPressed:(id)sender {

    AddNoteViewController *addNoteVC = [AddNoteViewController new];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
  // Return NO if you do not want the specified item to be editable.

    return YES;
}

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

    if (editingStyle == UITableViewCellEditingStyleDelete) {

        // Delete object from database

        [context deleteObject:[self.notes objectAtIndex:indexPath.row]];



        NSError *error = nil;

        if (![context save:&error]) {

            NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]);
           return;
        }

       // Remove device from table view

        [self.notes removeObjectAtIndex:indexPath.row];

        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

    }
}

- (IBAction)btnClick:(id)sender {
}

-(UITableViewCellEditingStyle) tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

//#pragma Search Methods

//

//- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope

//{

//    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", searchText];

//    //    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"contains[c] %@", searchText];

//    self.searchResults = [self.notes filteredArrayUsingPredicate:predicate];

//}

//

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

//{

//    [self filterContentForSearchText:searchString

//                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]

//                                      objectAtIndex:[self.searchDisplayController.searchBar

//                                                     selectedScopeButtonIndex]]];

//    

//    return YES;

//}

@end

1 个答案:

答案 0 :(得分:0)

在头文件

中为nsfetchviewcontroller创建属性
#import <UIKit/UIKit.h>

  @interface searchController : UIViewController<UITableViewDataSource,UITableViewDelegate,NSFetchedResultsControllerDelegate,UISearchBarDelegate,UISearchResultsUpdating,UISearchControllerDelegate,UITextFieldDelegate,UITextViewDelegate>{}

 @property(nonatomic,retain)NSFetchedResultsController *catefetchedResultsController;     

@property (nonatomic, retain) IBOutlet TypeTextfiled *searchCate;
@end 

将seachCate textfeild与xib文本字段连接,并将委托设置为视图控制器

在您的searchController.m文件中

执行此操作 catName,local_Id是我的cordata中的字段,我正在使用它们进行谓词查询,你可以使用自己的列名

  #pragma mark -  fetching
 - (NSFetchedResultsController *)fetchedResultsControllerCate
{
if (catefetchedResultsController == nil)
{
    NSManagedObjectContext* mangedobjectContext=[self appDelegate].managedObjectContext;
    NSEntityDescription *entity = [NSEntityDescription entityForName:frAddCategoryTable
                                              inManagedObjectContext:mangedobjectContext];


    NSFetchRequest *request= [[NSFetchRequest alloc] init];
    NSString*dateStr=[NSString stringWithFormat:@"%@",[UserDefaluts objectForKey:frautoIncrement]];

    NSPredicate *predicate =[NSPredicate predicateWithFormat:@"local_Id==%@",[DateValidator TimestapToDate:dateStr]];


    NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"local_Id" ascending:YES];
    NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:@"catName" ascending:YES];

    NSArray *sortDescriptors = [NSArray arrayWithObjects:sd1,sd2, nil];

    [request setSortDescriptors:sortDescriptors];
    [request setEntity:entity];
    [request setPredicate:predicate];

    [request setFetchBatchSize:10];

    catefetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                                       managedObjectContext:mangedobjectContext
                                                                         sectionNameKeyPath:nil
                                                                                  cacheName:nil];

    [catefetchedResultsController setDelegate:self];


    NSError *error = nil;
    if (![catefetchedResultsController performFetch:&error])
    {
        NSLog(@"Error performing fetch: %@", error);
    }
}

return catefetchedResultsController;

 }

我这是nsfetchview控制器的委托方法

  - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
 {
if (controller==catefetchedResultsController)
{
    [self.categoryTable reloadData];
}

 }

这里当您更改文本字段范围时,此删除操作将被唤醒 它将为NSPredicate调用filterCate方法

 - (BOOL)textField:(TypeTextfiled *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

NSString * searchStr = [textField.text stringByReplacingCharactersInRange:range withString:string];

if(textField == self.searchCate){

    [self filterCate:searchStr];

}
return true;
}

请根据您的要求更改NSPredicate并更改名称

 -(void)filterCate:(NSString*)text
 {
filteredTableData = [[NSMutableArray alloc] init];

// Create our fetch request
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

// Define the entity we are looking for

NSManagedObjectContext* mangedobjectContext=[self appDelegate].managedObjectContext;
NSEntityDescription *entity = [NSEntityDescription entityForName:frCategoriesTable
                                          inManagedObjectContext:mangedobjectContext];


[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"special==%i",0];
[fetchRequest setPredicate:predicate];



// If we are searching for anything...
if(text.length > 0)
{
    // Define how we want our entities to be filtered
    predicate = [NSPredicate predicateWithFormat:@"(catName CONTAINS[c] %@ AND special==%i)", text,0];
    [fetchRequest setPredicate:predicate];
}
NSError *error;

// Finally, perform the load
NSArray* loadedEntities = [mangedobjectContext executeFetchRequest:fetchRequest error:&error];
filteredTableData = [[NSMutableArray alloc] initWithArray:loadedEntities];

[self.CategorTable reloadData];
 }

表格视图

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectionIndex {
 #warning Incomplete method implementation.



 NSArray *sectionCate = [[self fetchedResultsControllerCate] sections];


 if (tableView==self.categoryTable) {


    if (sectionIndex < [sectionCate count])
    {
        id <NSFetchedResultsSectionInfo> sectionInfo = [sectionCate objectAtIndex:sectionIndex];


        return sectionInfo.numberOfObjects;

      }
  }

  return 0;

}

  -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
 {

    return 70;
 }


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

tableView.backgroundColor=[UIColor whiteColor];
static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.selectionStyle=UITableViewCellSelectionStyleNone;
tableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
tableView.separatorColor=[UIColor colorWithRed:216.0/255.0f green:216.0/255.0f blue:216.0/255.0f alpha:1.0/1.0f];

   if(tableView==self.categoryTable){

      cell=[self CategoryTablecreateCellFor:cell CellindexPath:indexPath];
  }

return cell;
  }




   -(UITableViewCell*)CategoryTablecreateCellFor:(UITableViewCell*)cell CellindexPath:(NSIndexPath*)indexPath{
 AddCategory*cateRecipe=(AddCategory*)[[self fetchedResultsControllerCate] objectAtIndexPath:indexPath];


UILabel *txt=[[UILabel alloc] initWithFrame:CGRectMake(130, 0, 150, 70)];
 txt.text=cateRecipe.catName;
txt.textColor=[UIColor darkGrayColor];
[txt setFont: [UIFont fontWithName:@"Helvetica" size:15.0]];




  cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;

 [cell.contentView addSubview:txt];


 return cell;
   }