Search code examples
iosswiftuistoryboardseguexcode6.1

Pass indexPath via Segue


I am trying to pass the indexPath of a NSManagedObject via a segue (show) so in the destination I can have dynamic information shown. I have tried multiple ways, but have gotten errors for all of them. This is the method I am currently trying, but it is not working. Could someone please explain what I'm doing wrong and/or what the most effective way to do this?

numberOfRowsInSection & prepareForSegue code in source View Controller

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)
    }
}

Error (occurs when calling tableView.indexPathForCell): '(UITableView, numberOfRowsInSection: Int) -> Int' does not have a member named 'indexPathForCell'.

Is there something I need to add to the numberOfRowsInSection function?

Destination View Controller Code

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()
}

}

Error (occurs when calling objectives in declaring obj): 'ObjectiveDetailViewController.Type' does not have a member named 'objectives'.

This error I have no clue what is wrong because I clearly have initiated the objectives array. Have I declared something incorrectly or have I not given enough information?


Solution

  • I believe the first error (despite that weird error message) has nothing to do with numberOfRowsInSection. Since the sender is a conditional AnyObject, you need to unwrap it, and downcast it:

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

    The second error is caused by accessing your array outside of a method. You should move that line into viewDidLoad (and you need to unwrap indexPath as well),

    override func viewDidLoad() {
        super.viewDidLoad()
        var obj = objectives[indexPath!.row]
    }
    

    There's another problem with that, though, because you haven't added any NSManagedObjects to your array before you try to access it.

    Probably, what you want to do though, is to pass the managed object that was selected in the table view, not pass the indexPath.