问题
I need to update a variable in a TableViewController and I can't find the way to do it, can someone explain me why this is not working please? I'm getting mad.

From my view controller this is the code I'm running:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let TV = storyboard.instantiateViewControllerWithIdentifier("tbController") as myTableViewController
TV.x = "test"
And then, from the TableViewController class:
class myTableViewController: UITableViewController {
var x:String!
override func viewDidLoad() {
super.viewDidLoad()
println("Value of x is: \(self.x)")
}
}
And the printed value is: nil
Why? What is wrong with that? I don't understand :-(
Updated Picture

回答1:
First, give the segue between the ViewController and the TableViewController an identifier (Example: "TableViewSegue"
Then in the ViewController, use prepareForSegue
to pass data from ViewController to TableViewController
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "TableViewSegue" {
let vc = segue.destinationViewController as myTableViewController
vc.x = "Test"
}
}
回答2:
There could be several issues here.
1. You should embed the tableview into the initial viewcontroller and create it as an IBOutlet
Edit: from the updated picture it appears that you want to click the top right button and go to the tableview. Therefore, this is an incorrect statement.
- You also need to make your Viewcontroller (either the tableviewcontroller or the main viewcontroller if you chose to follow #1 above) a UITableViewDelegate and UITableViewDataSource
- If you are expecting to change the label listed on the image shown, you will need to use label.text = "String" assignment to change what is displayed there
- You have not set an initial variable for x inside the tableviewcontroller.
Also, as a point, your order of operations isn't properly set, so it will always display nil. Because if you look at how you built this:
- You have a println inside of a viewdidload on the tableview. This variable you are printing has NOT been set yet, so it is nil
- You then created an instance of this class. As soon as you created that instance, the viewdidload method fired and it printed a nil line.
- THEN you changed the variable via the TV.x method. But there is no println check there so you're not able to see what you did.
来源:https://stackoverflow.com/questions/26533449/update-a-variable-in-a-tableviewcontroller