我试图将一个值从一个视图控制器传递到另一个视图控制器,但它在第二个视图控制器中显示为nil。
下面是设置变量值的代码,它也设置了第二个视图控制变量的值:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "TestChat") as! TestChat
let user2Name = name[indexPath.row]
let user2Info = ref.child("Users").child((myuser?.uid)!).child("Contacts")
user2Info.observe(.value, with: {(snapshot) in
let enumerator = snapshot.children
while let rest = enumerator.nextObject() as? FIRDataSnapshot {
print(String(describing: rest.value))
if((rest.childSnapshot(forPath: "/Name").value as! String) == user2Name) {
//this means that it has iterated to the correct user
self.user2cred = String(rest.key)
print(self.user2cred as! String)
DispatchQueue.main.async {
//below sets the value of numbers on the next view controller
let vc = self.storyboard?.instantiateViewController(withIdentifier: "TestChat") as! TestChat
print("this should be the credentials")
print(self.user2cred!)
vc.otherUserID = self.user2cred
}
} else {
print("doing nothing doing nothing")
//do NOTHING this is the wrong user being iterated on
}
}
})
self.present(vc, animated: true, completion: nil)
}
第二个视图控制器如图所示:
class TestChat: UIViewController, UITableViewDelegate, UITableViewDataSource, SBDConnectionDelegate, SBDChannelDelegate {
var otherUserID: String?
...
override func viewDidLoad() {
super.viewDidLoad()
print(self.otherUserID)
}
在分配第二个视图控制器的值之前直接打印的值打印它应该打印的值,但是当在第二个视图控制器中打印该值时,打印“nil”