在 ViewController 之间传递 NSManagedObject

Passing a NSManagedObject between ViewControllers

我正在尝试在 2 ViewControllers 之间传递一个 NSManagedObject。 为此,我使用了一个全局变量。

在第一个viewcontroller我有,在最上面(作为一个全局变量):

var choosenItem : NSManagedObject? = nil

我构建了我的 table 视图并且我有这个:

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)

}

当我打印所选的 objectId 时,我得到了它们。所以我认为 ViewController 一切正常。

在 ViewController2 中我有这个:

   override func viewDidLoad() {

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

}

现在我不确定为什么我在第二个 ViewController 中得到 nil。 有没有办法像这样传递 NSManagedObject

您需要通过将 choosenItem 分配给 ViewController2thatLand 属性 来传递它,您还需要明确地将 UIViewController 转换为 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)