我正在尝试通过segue(显示)传递NSManagedObject的indexPath,以便在目标位置显示动态信息。我尝试了多种方法,但是都遇到了错误。这是我目前正在尝试的方法,但是没有用。有人可以解释我做错了什么,和/或最有效的方法是什么?
源代码视图控制器中的numberOfRowsInSection和prepareForSegue代码

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return objectives.count
}

...

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let controller = segue.destinationViewController as ObjectiveDetailViewController
    if segue.identifier == "ObjectiePrototypeCell" {
        controller.indexPath = self.tableView.indexPathForCell(sender)
    }
}
错误(在调用tableView.indexPathForCell时发生):'((UITableView,numberOfRowsInSection:Int)-> Int'没有名为'indexPathForCell'的成员。
我需要在numberOfRowsInSection函数中添加一些内容吗?
目标视图控制器代码
import UIKit
import CoreData

class ObjectiveDetailViewController: UIViewController {

var objectives = [NSManagedObject]()
var indexPath: NSIndexPath?
lazy var managedContext: NSManagedObjectContext = {
    let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    let managedContext = appDelegate.managedObjectContext
    return managedContext!
    }()

var obj = objectives[indexPath.row]

override func viewDidLoad() {
    super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

}
错误(在声明obj时调用目标时发生):'ObjectiveDetailViewController.Type'没有名为'objectives'的成员。
我不知道这个错误是什么错误,因为我显然已经启动了目标数组。我是否声明了错误的信息或没有提供足够的信息?

最佳答案

我相信第一个错误(尽管有奇怪的错误消息)与numberOfRowsInSection无关。由于发件人是有条件的AnyObject,因此您需要将其拆开并下投:

controller.indexPath = self.tableView.indexPathForCell(sender! as UITableViewCell)

第二个错误是由于在方法外部访问数组引起的。您应该将该行移到viewDidLoad中(并且还需要解开indexPath),
override func viewDidLoad() {
    super.viewDidLoad()
    var obj = objectives[indexPath!.row]
}

但是,还有另一个问题,因为在尝试访问它之前,尚未将任何NSManagedObjects添加到您的数组中。

不过,您可能要做的是传递在表视图中选择的托管对象,而不传递indexPath。

07-28 01:29