Swift使用NSFetchedResultsController和UISearchBarDelegate [英] Swift Using NSFetchedResultsController and UISearchBarDelegate

查看:254
本文介绍了Swift使用NSFetchedResultsController和UISearchBarDelegate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找这个问题的一个体面的解决方案。我想在TableView上实现一些简单的搜索功能。

I am looking for a decent solution to this problem. I am wanting to implement some simple search functionality on a TableView that I have.

我发现的所有示例都使用已弃用的 UISearchDisplayController 或使用新的 UISearchController 但没有 NSFetchedResultsController
目前使用核心数据 / NSFetchedResultsController

All the examples I have found either use the deprecated UISearchDisplayController or use the new UISearchController but without NSFetchedResultsController Currently this is populated using Core Data / NSFetchedResultsController

它到一个点,我可以收集用户的搜索字符串(woo!)。我知道我可能需要一个单独的 FRC 来执行搜索,但如上所述,迄今为止所有尝试失败。

So far I have managed to get it to a point where I can gather the users' search string (woo!). I am aware that I may need a separate FRC to perform the search on, but as mentioned above all attempts up to now have failed.

我的类符合以下协议:

class JobListController: UIViewController, UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate, UISearchBarDelegate{

我不能使用 UITableViewController 因为我已经写了一些现有的功能,依赖于这个类是 UIViewController
我有我的两个 IBOutlets

I can't use UITableViewController as I have already written loads of existing functionality that relies on this class being a UIViewController I have my two IBOutlets:

@IBOutlet var tblJobs : UITableView!
@IBOutlet weak var searchBar: UISearchBar!

和我的空数组来保存我的各种核心数据 bits and bobs:

and my empty arrays to hold my various Core Data bits and bobs:

var workItems = [Work]()
var filteredWorkItems = [Work]()

这是我初始化我的 FRC ,和我的 MOC ,我留在我的空的第二个 FRC ,因为我相当肯定,

Here is how I am initialising my FRC, along with my MOC and I've left in my empty second FRC as I am quite sure it will be needed at some point:

  let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

lazy var fetchedResultsController: NSFetchedResultsController = {
    let workFetchRequest = NSFetchRequest(entityName: "Work")
    let primarySortDescriptor = NSSortDescriptor(key: "createdDate", ascending: true)
    let secondarySortDescriptor = NSSortDescriptor(key: "town", ascending: true)
    workFetchRequest.sortDescriptors = [primarySortDescriptor, secondarySortDescriptor]

    let frc = NSFetchedResultsController(
        fetchRequest: workFetchRequest,
        managedObjectContext: self.managedObjectContext!,
        sectionNameKeyPath: "createdDate",
        cacheName: nil)

    frc.delegate = self


    return frc
    }()

var searchResultsController: NSFetchedResultsController?

在我的 viewDidLoad 我的表和searchBar的委托/数据源:

In my viewDidLoad function I am setting up the delegates / data source for my table and the searchBar:

  tblJobs.delegate = self
  tblJobs.dataSource = self
  searchBar.delegate = self

这里是 searchBar 函数,这是我在哪里。 stringMatch 变量是从以前的尝试中遗漏,我希望能够通过多个不同的参数搜索,但是如果我可以得到只有一个工作,它将一个坚实的开始。

and here is the searchBar function which is where I am up to. The stringMatch variable is leftover from a previous attempt, I am hoping to be able to search by a multitude of different parameters here, but if I can get just one working it will be a solid start.

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
    println("Search text is \(searchText)")
    self.filteredWorkItems = self.workItems.filter({( work: Work) -> Bool in
        //
        let stringMatch = work.postcode.rangeOfString(searchText)
        return stringMatch != nil
    })

    if(filteredWorkItems.count == 0){
        searchActive = false;
    } else {
        searchActive = true;
    }
    self.tblJobs.reloadData()
}

这是我的 cellForRowAtIndexPath 函数,显示我如何从 fetchedResultsController

Here is my cellForRowAtIndexPath function to show how I am pulling data from the fetchedResultsController

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    let cell =  self.tblJobs.dequeueReusableCellWithIdentifier(
        "JobCell", forIndexPath: indexPath)
        as! JobTableViewCell

    let workItem = fetchedResultsController.objectAtIndexPath(indexPath) as! Work



 //...

    return cell
}

所以你可以看到我有一些东西在这里,最终我想知道我如何使用我的新获得 searchText 字符串查询我的 FRC ,然后结果在View中正确过滤。

So you can see I've got a few things going on here, ultimately I am wanting to figure out how I use my newly gotten searchText string to query against my FRC, and then for the results to filter properly in the View.

更新:

我已尝试将搜索字符串添加到我的 NSPredicate FRC 像这样:

I have attempted to add the search string to my NSPredicate in the FRC like so:

lazy var fetchedResultsController: NSFetchedResultsController = {

   ../


    workFetchRequest.predicate = NSPredicate(format:"title contains[cd] %@", savedSearchTerm!)

   //...
    return frc
    }()

这导致'JobListController.Type'没有名为savedSearchTerm的成员

我的类我设置了这样:

var savedSearchTerm: NSString?

那么不知道我做错了什么?

So not sure what I'm doing wrong?

推荐答案

从您的代码中,我假设您想使用相同表视图显示结果。因此,您只需要根据搜索字词使用新的过滤器更新您的FRC。

From your code, I assume you want to use the same table view to display the results. So you just need to update your FRC with a new filter based on the search term.

将搜索字词存储在变量中。在FRC工厂函数中,包括谓词,如下所示:

Store the search term in a variable. In the FRC factory function, include the predicate, something like this:

request.predicate = searchText?.characters.count > 0 ?
 NSPredicate(format:"title contains[cd] %@", searchText!) : nil

当文本更改时,重置FRC并重新加载。

When the text changes, reset the FRC and reload.

fetchedResultsController = nil
tableView.reloadData()

如果您有其他过滤器,例如范围按钮,请在谓词中添加其他术语。

If you have additional filters, such as scope buttons, add additional terms to the predicate.

这篇关于Swift使用NSFetchedResultsController和UISearchBarDelegate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆