简体   繁体   中英

Swift Using NSFetchedResultsController to update TableView

I have an NSFetchedResultsController that is populating a TableView . The TableView is using custom cells.

When I search I am getting the correct results but the TableView isn't getting updated, any ideas?

func controller(
    controller: NSFetchedResultsController,
    didChangeObject anObject: AnyObject,
    atIndexPath indexPath: NSIndexPath?,
    forChangeType type: NSFetchedResultsChangeType,
    newIndexPath: NSIndexPath?) {

        switch type {
        case NSFetchedResultsChangeType.Insert:
            if let insertIndexPath = newIndexPath {
                self.tblJobs.insertRowsAtIndexPaths([insertIndexPath], withRowAnimation: UITableViewRowAnimation.Fade)
            }
        case NSFetchedResultsChangeType.Delete:
            if let deleteIndexPath = indexPath {
                self.tblJobs.deleteRowsAtIndexPaths([deleteIndexPath], withRowAnimation: UITableViewRowAnimation.Fade)
            }
        case NSFetchedResultsChangeType.Update:
            // Note that for Update, we update the row at __indexPath__
            if let updateIndexPath = indexPath {
                let cell =  self.tblJobs.dequeueReusableCellWithIdentifier(
                    "JobCell")
                    as! JobTableViewCell
                //let cell = self.tblJobs.cellForRowAtIndexPath(updateIndexPath)
                let workItem = self.fetchedResultsController.objectAtIndexPath(updateIndexPath) as? Work

            }

And heres my search function:

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
        println("Search text is \(searchText)")
      savedSearchTerm = searchText


        if(savedSearchTerm!.length == 0){
            searchActive = false;
        } else {
            searchActive = true;


             self.fetchedResultsController.fetchRequest.predicate = NSPredicate(format:"town CONTAINS[cd] %@", savedSearchTerm!)

            var error: NSError? = nil
            self.fetchedResultsController.performFetch(&error)
            if (error != nil) {
                NSLog("Unable to perform fetch.")
                NSLog("%@, %@", error!, error!.localizedDescription)
            }else{

               var  filteredWorkItems = self.fetchedResultsController.fetchedObjects

                println("fetched objects are: \(filteredWorkItems)")

            }
             self.tblJobs.reloadData()
        }


    }

Update, cellForRowAtIndexPath function

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    println("getting hit")

    let cell =  self.tblJobs.dequeueReusableCellWithIdentifier(
        "JobCell")
        as! JobTableViewCell

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

    var parties: NSSet = workItem.parties

    var arr = parties.allObjects //Swift Array

    var party = arr.first as! Party

    var partyName = "\(party.title.desc) \(party.firstName) \(party.lastName)"




    cell.lblAddress?.text = "\(workItem.propertyNumber) \(workItem.street) \(workItem.town) \(workItem.locality) \(workItem.postcode)"

    cell.lblSchemeType?.text = workItem.scheme.desc

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd/MM/YY"



    let dateString = dateFormatter.stringFromDate(workItem.createdDate)

    cell.lblCreatedDate?.text = dateString
    cell.lblPartyDetails?.text = partyName



    return cell
}

You can use the same table for searching and for displaying. You need to disable the superimposed table view (the UISearchController interface).

You need to not use a UISearchController , just the UISearchBar . Use its UISearchBarDelegate methods to trigger updates of the original table.

Unfortunately this was a blunder on my part, the reason I was able to view the section title but no actual rows were being displayed was because I had left a silly boolean check in my numberOfRowsInSection function from a previous attempt at getting this to work:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    // return workItems.count
    if searchActive{
    return filteredWorkItems.count
    }
    if let sections = fetchedResultsController.sections {
        let currentSection = sections[section] as! NSFetchedResultsSectionInfo
        return currentSection.numberOfObjects
    }

    return 0

}

I removed that if searchActive block and the info magically displayed, as the FRC and TableView were already doing what they were supposed to

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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