H.N. H.N. - 1 year ago 77
Swift Question

Passing a NSManagedObject between ViewControllers

I am trying to pass a

between 2
For this I am using a global variable.

In the first
I have, on the top (as a global variable):

var choosenItem : NSManagedObject? = nil

I build my table view and i have this:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

let choosenOne = listOfLands[indexPath.row]
let choosenItem = listOfLands[indexPath.row]

let viewController = storyboard?.instantiateViewController(withIdentifier: "ViewController2")
self.navigationController?.pushViewController(viewController!, animated: true)



when I print the chosen objectId I got them. so I think in this
everything is working ok.

In ViewController2 I have this:

override func viewDidLoad() {

print(thatLand?.objectID) //result is nil


Now I am not sure why I get nil in the second
Is there a way to pass the
like this?

Answer Source

You need to pass that choosenItem by assigning it to the thatLand property of ViewController2 also you need to explicitly cast the UIViewController to ViewController2.

let viewController = storyboard?.instantiateViewController(withIdentifier: "ViewController2") as! ViewCotroller2 //Cast as ViewController name

//Now set thatLand property with your array's selected object before pushing it to Navigation stack
viewController.thatLand = listOfLands[indexPath.row]

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