2016-11-22 35 views
1

我想通过一个NSManagedObject之间2 ViewControllers。 为此,我使用了一个全局变量。ViewControllers之间传递一个NSManagedObject

在第一viewcontroller我有,在顶部(作为全局变量):

var choosenItem : NSManagedObject? = nil 

我建立我表视图,我有这样的:

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得到零。 有没有办法通过这样的NSManagedObject

回答

1

您需要通过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) 
+0

做到了。现在,当我这样做“viewController.thatLand = listOfLands [indexPath.row]”我收到一条消息,说ViewController2没有成员“thatLand”。我如何在vc2中初始化“thatLand”? –

+0

@ H.N。我在谈论这个'print(thatLand?.objectID)'你提到了你的问题。 –

+0

我也是,我告诉过你。我认为没关系。但是现在我得到“类型ViewController2的值不是成员thatLand”。 –

相关问题