Swalsz Swalsz - 2 years ago 94
Swift Question

Pass data between controller without any kind of storyboard reference

I'm trying to pass data between a tableview and a viewcontroller.
For reason that i don't repeat here, I created the view controller programmatically, just via code and without any kind of reference and presence in the storyboard (I have not the ViewController in the Storyboard). Everything work fine, also the graphical transition, but the data transition.
I performed the data transition in "didSelectRowAtIndexPath" before the graphical transition.

In ViewController

var purchase:Purchase?

In TableViewController

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

var arrayToUse:NSArray?
var tableInUse:UITableView?
let dc = DetailsViewController()

// Retrive the correct data here

let indexPath = tableInUse?.indexPathForSelectedRow
dc.purchase = arrayToUse?.objectAtIndex((indexPath?.row)!) as! Purchase
let temp = arrayToUse?.objectAtIndex((indexPath?.row)!) as! Purchase

self.navigationController!.pushViewController(DetailsViewController(), animated: true)

I looked at different solution found here and in other site, but I always found solution contemplating "segue" or "nib".
What I'm doing wrong?

I hope that I made clear
Every kind of help or tips are really welcome.


Answer Source

The issue is you are creating an instance of DetailsViewController and setting the data to it, but pushing another DetailsViewController object. You should use previously created dc object instead of creating a new instance.

Instead of:

self.navigationController!.pushViewController(DetailsViewController(), animated: true)

You should use:

self.navigationController!.pushViewController(dc, animated: true)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download