将 NSFetchedResultsControllerDelegate 与核心数据一起使用时,iOS Swift 的 didSelectRowAtIndexPath 方法未触发?

标签 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.
    }
    */

}

最佳答案

您忘记将 UITableViewDelegate 分配给 UITableView:

theTableView.delegate = self

尝试在theTableView.dataSource = self下面赋值

关于将 NSFetchedResultsControllerDelegate 与核心数据一起使用时,iOS Swift 的 didSelectRowAtIndexPath 方法未触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26600385/

相关文章:

ios - 如何在 PDFKit 中突出显示搜索结果 - iOS

arrays - 平面嵌套对象的闭包?

ios - 使用 NsPredicate 解析查询后的 If 语句

ios - 编程等效于 UIViewController 的 "Resize View From NIB"属性

ios - 无法在 UIDocumentInteractionController/UIWebView 中显示 .xlsx 甲酸盐

ios - 滚动 UITableView 以关闭 UIView Above

ios - 使用 UITableView 发出分页

ios - 如何使用 CoreData 信息对 UITableView 进行排序

objective-c - 按下按钮上传下一个 View 或 webview 时如何显示事件指示器?

iphone - 在 Objective-C 类别中使用静态变量