Need help adding data to a TableView

88 views Asked by At

My first View Controller has a TableView.

On a second view controller, the user will input data and click a button.

I want this button to add the data to the table view, but I can not figure out how to do this.

var textArray: NSMutableArray! = NSMutableArray()

@IBOutlet weak var tableView: UITableView!

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.textArray.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    return UITableViewCell()
}



@IBOutlet weak var addData: UIButton!

@IBAction func addData(sender: AnyObject) {

    self.textArray.addObject(textField.text)
    self.tableView.reloadData()

}

It also brings up an error for my reloadData line of code.

2

There are 2 answers

1
Mika On

Presumably the code you have quoted is in the second view controller. The IBAction in that view controller can't reload the self.tableview because that table is in the first view controller.

To do what you are looking to so there are literally dozens of approaches each with pluses and minuses. Maybe the easiest to implement is:

  1. Creating a public variable in your second view controller called textArray.
  2. Set the public variable in the prepareForSegue to the data source of the table in the first view controller.
  3. Add the string to that variable in the IBAction of the second view controller self.textArray.addObject(textField.text).
  4. add the self.tableView.reloadData() line to the viewWillAppear function of the first view controller.
1
Mr UziBazooka On

If you want the user to be able to save data in one view, and then load that data in another view, you need to save the data ether locally, or on a server. To save in locally you can use NSUserdefault.

Let the user add obejcts to an array. Then save the array on the phone to load it later, using NSUserdefault.

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("yourArray", forKey: "nameYourArrayToGetItLater")
defaults.synchronize()

And use this code to get it back, and load it in to your TableView.

let defaults = NSUserDefaults.standardUserDefaults()
defaults.stringForKey("nameYourArrayToGetItLater")
"yourArrayforTheTabelView" = defaults

If you want to store your TableView data on a server. You might want to look at this tutorial:

http://www.appcoda.com/ios-programming-app-backend-parse/

Good luck!