Search code examples
iosswiftcore-dataswift3nsmanagedobject

Passing a NSManagedObject between ViewControllers


I am trying to pass a NSManagedObject between 2 ViewControllers. For this I am using a global variable.

In the first viewcontroller 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)

    print(choosenOne.objectID)
    print(choosenItem.objectID)

}

when I print the chosen objectId I got them. so I think in this ViewController 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 ViewController. Is there a way to pass the NSManagedObject like this?


Solution

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