当使用NSFetchedResultsControllerDelegate与Core Data时,iOS Swift的didSelectRowAtIndexPath方法没有触发?

时间:2014-10-28 03:24:02

标签: ios uitableview swift

对于我的生活,我无法弄清楚为什么didSelectRowAtIndexPath方法不起作用。我已经尝试过我能想到的一切。

我真的只是在按下一个单元格时尝试将字符串记录到控制台。感谢。

import UIKit
import CoreData

class TableViewController: UIViewController, UITableViewDataSource, NSFetchedResultsControllerDelegate, UITableViewDelegate {

    struct TableViewConstants {

        static let cellIdentifier = "Cell"

    }

    var frc:NSFetchedResultsController!

    var managedObjectContext:NSManagedObjectContext? {
        return (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext
    }

    let fetchRequest = NSFetchRequest(entityName: "Shortcut")

    let shortcutSort = NSSortDescriptor(key: "shortcut", ascending: false)

    var refreshControl:UIRefreshControl?

    func handleRefresh(paramSender: AnyObject) {

        let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_SEC))
        dispatch_after(popTime, dispatch_get_main_queue(), {
            self.refreshControl!.endRefreshing()
        })

    }

    var tableView: UITableView?

    override func viewDidLoad() {

        super.viewDidLoad()

        fetchRequest.sortDescriptors = [shortcutSort]

        frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil)

        frc.delegate = self

        var fetchingError:NSError?

        if frc.performFetch(&fetchingError) {

            println("Successful fetch...")

        } else {

            println("Failed fetch...")

        }

        tableView = UITableView(frame: view.bounds, style: .Plain)

        if let theTableView = tableView {
            theTableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier:"identifier")
            theTableView.dataSource = self
            theTableView.autoresizingMask = .FlexibleWidth | .FlexibleHeight

            refreshControl = UIRefreshControl()
            refreshControl!.addTarget(self, action: "handleRefresh:", forControlEvents: .ValueChanged)

            theTableView.addSubview(refreshControl!)

            view.addSubview(theTableView)
        }

        //...
        // performSegueWithIdentifier("View", sender: nil)
        // Do any additional setup after loading the view.
    }

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

    func controllerWillChangeContent(controller: NSFetchedResultsController) {

        tableView?.beginUpdates()

    }

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

        if type == .Delete {

            tableView?.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)

        } else if type == .Insert {

            tableView?.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)

        }

    }

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

        let sectionInfo = frc.sections![section] as NSFetchedResultsSectionInfo

        return sectionInfo.numberOfObjects

    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("identifier", forIndexPath: indexPath) as UITableViewCell

        let shortcut = frc.objectAtIndexPath(indexPath) as Shortcut

        cell.textLabel.text = shortcut.shortcut

        //...

        return cell

    }

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        let alert = UIAlertController(title: "Item selected", message: "You selected item \(indexPath.row)", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
    }

    func tableView(tableView: UITableView!, editingStyleForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCellEditingStyle {
        return .Delete
    }

    override func setEditing(editing: Bool, animated: Bool) {

        super.setEditing(editing, animated: animated)
        tableView!.setEditing(editing, animated: animated)

    }

    func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
        if editingStyle == .Delete {

            let shortcutToDelete = self.frc.objectAtIndexPath(indexPath) as Shortcut

            managedObjectContext!.deleteObject(shortcutToDelete)

            if shortcutToDelete.deleted {

                var savingError:NSError?

                if managedObjectContext!.save(&savingError) {

                    println("Object deleted...")

                } else {

                    if let error = savingError {

                        println("Error: \(error)")

                    }

                }

            }

        }

    }

    /*func editTableViewRows() {

    }*/

    func controllerDidChangeContent(controller: NSFetchedResultsController) {

        tableView?.endUpdates()

    }

    override func prefersStatusBarHidden() -> Bool {

        return true

    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
    }
    */

}

1 个答案:

答案 0 :(得分:3)

您忘了将UITableViewDelegate分配给UITableView:

theTableView.delegate = self

尝试将其分配到theTableView.dataSource = self

以下