1

I am trying to create a simple app which lets appending data into an array in first ViewController and then send it to the SecondViewController through the segue. However instead of appending new data it is updating first index of an array.

import UIKit


class ViewController: UIViewController {

var data = [String]()

@IBOutlet weak var textField: UITextField!


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

@IBAction func sendButton(_ sender: Any) {
    if textField.text != nil {
        let activity = textField.text
        data.append(activity!) //Data should be appended here.
        performSegue(withIdentifier: "sendSegue", sender: self)
    }

}


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "sendSegue" {
        let destVC: AppTableViewController = segue.destination as! AppTableViewController
        destVC.newData = data
    }
}


}

Here is my SecondTableViewController and it just update first index so I am just keep changing my first index instead of adding new values into it.

import UIKit

class AppTableViewController: UITableViewController {

var newData = [String]()

@IBOutlet var myTableView: UITableView!

override func viewDidLoad() {
super.viewDidLoad()

}



override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return newData.count
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

cell.textLabel?.text = newData[indexPath.row]

return cell
}


}
  • How are you adding data to the data array? – Martin Muldoon Oct 29 '17 at 21:46
  • Because var data = [String]() always initialized when get back from second VC. if you want to keep adding, declare "data" global variable and need to removeAll in somewhere to clear. – Yongjoon Oct 29 '17 at 21:56

1 Answers1

0

Based on this link,

Please change the function name sendButton to btnSendButton. So that it will run before prepare.

As of now sendButton is running after prepare. So the data is not appending.

Vini App
  • 7,339
  • 2
  • 26
  • 43
  • I am trying to do this but every time I am trying to change IBAction name to something else through the ViewController's code I am keep getting crash which navigates me back to Debug Navigator. What is a proper way of changing that function's name to avoid a crash? –  Oct 30 '17 at 11:58