简体   繁体   English

如何从可从coredata加载数据的表视图中搜索

[英]How to Search from a tableview which loads data from coredata

The code for my view controller is given below. 我的视图控制器的代码如下。

The tableview is loading data from core data. tableview正在从核心数据加载数据。

I have added a searchbar to the viewcontroller.Can anyone help me to implement search in this?? 我已经在viewcontroller中添加了搜索栏。有人可以帮我实现搜索吗? I am confused looking at tutorials .please can anyone provide the solution for this 我对教程感到困惑。请任何人可以为此提供解决方案

import UIKit

import CoreData

class NotesListTableViewController: UITableViewController  ,UISearchBarDelegate 

{

@IBOutlet weak var searchBar: UISearchBar!
var managedObjectContext : NSManagedObjectContext!
var entries: [NSManagedObject]!
override func viewDidLoad()
{
    super.viewDidLoad()


    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    managedObjectContext = appDelegate.managedObjectContext
    //self.fetchEntries()

          // makes the searchbar stay in the current screen and not spill into the next screen
    definesPresentationContext = true

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem()
}


   override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source



override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{

    return self.entries.count


}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
    return 1
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCellWithIdentifier("NotesCell", forIndexPath: indexPath)

    // Configure the cell...
               let entry1 = entries[indexPath.row]
        cell.textLabel?.text = entry1.valueForKey("entry_title") as? String


        let imageData2 = entry1.valueForKey("entry_image") as? NSData

        if let imageData2 = imageData2
        {
            let myimage = UIImage(data:imageData2,scale:1.0)
            cell.imageView?.image = myimage
        }


    return cell

}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
    if segue.identifier! == "showNote"
    {
        let detailDisplay = segue.destinationViewController as! DetailDisplayViewController
        let selectedIndexPath = tableView.indexPathForSelectedRow!
        let entry = entries[selectedIndexPath.row]
        detailDisplay.entry = entry
    }
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
    let entry1 = self.entries[indexPath.row]
    self.managedObjectContext.deleteObject(entry1)
    self.entries.removeAtIndex(indexPath.row)
    self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
    do
    {
        try managedObjectContext.save()
    } catch  {
        print ("could not save the new entry ")
    }


}
override func viewWillAppear(animated: Bool)
{
    super.viewWillAppear(animated)
    self.fetchEntries()

}

func fetchEntries()
{
    let fetchRequest = NSFetchRequest(entityName:"Entry")
    do {
        let entryObjects = try managedObjectContext.executeFetchRequest(fetchRequest)
        self.entries = entryObjects as! [NSManagedObject]
    }catch let error as NSError
    {
        print ("could not save the new entry \(error.description) ")
    }
    tableView.reloadData()
}
}

// you need to maintain two arrays, try like this //您需要维护两个数组,像这样尝试

func fetchEntries()
{
let fetchRequest = NSFetchRequest(entityName:"Entry")
do {
    let entryObjects = try managedObjectContext.executeFetchRequest(fetchRequest)
    self.entries = entryObjects as! [NSManagedObject]
}catch let error as NSError
{
    print ("could not save the new entry \(error.description) ")
}
self.arrOriginalList =  self.entries
tableView.reloadData()
}


- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[searchBar resignFirstResponder];
self.entries = [NSMutableArray arrayWithArray:self.arrOriginalList];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"entry_title.lowercaseString  BEGINSWITH[C] %@", [searchBar.text lowercaseString]];


self.entries= [NSMutableArray arrayWithArray:[self.entries filteredArrayUsingPredicate:predicate]
                ];



if([searchBar.text isEqualToString:@""]){

    self.entries = [NSMutableArray arrayWithArray:self.arrOriginalList];

}

[tableView reloadData];

 }

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
if([searchBar.text isEqualToString:@""]){

 self.entries = [NSMutableArray arrayWithArray:self.arrOriginalList];
 [tableView reloadData];

      }



}

// in swift try like this //快速尝试像这样

func fetchEntries()
{
 let fetchRequest = NSFetchRequest(entityName:"Entry")
do {
let entryObjects = try managedObjectContext.executeFetchRequest(fetchRequest)
self.entries = entryObjects as! [NSManagedObject]
}catch let error as NSError
{
   print ("could not save the new entry \(error.description) ")
}
self.arrOriginalList =  self.entries
tableView.reloadData()
}


 func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    searchBar.resignFirstResponder()
    self.entries = NSMutableArray(array:self.arrOriginalList)
    let predicate: NSPredicate = NSPredicate(format:"entry_title.lowercaseString  BEGINSWITH[C] %@", searchBar.text!.lowercaseString)
    self.entries= NSMutableArray(array:self.entries.filteredArrayUsingPredicate(predicate))
    if searchBar.text == "" {

        self.entries = NSMutableArray(array:self.arrOriginalList)
    }
    tableView.reloadData()
}

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
    if searchBar.text == "" {
        self.entries = NSMutableArray(array:self.arrOriginalList)
        tableView.reloadData()

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM