I am creating a simple to do list for iOS in xcode and I have run into a problem when trying to get the table view to reload when tabs are switched. I have written this into the view controller:
override func viewDidAppear(_ animated: Bool) {
let itemsObject = UserDefaults.standard.object(forKey: "items")
if let tempItems = itemsObject as? NSMutableArray {
items = tempItems
}
table.reloadData()
}
And I have added the table outlet as follows:
class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var table: UITableView!
The items are all being permanently stored using UserDefaults correctly and when I restart the app the new items I am adding do appear. But I cannot work out why this reload method is not working for me.
FULL CODE ADDED:
First view controller:
import UIKit
class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var table: UITableView!
var items:NSMutableArray = []
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "Cell")
cell.textLabel?.text = items[indexPath.row] as? String
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
let itemsObject = UserDefaults.standard.object(forKey: "items")
if let tempItems = itemsObject as? NSMutableArray {
items = tempItems
}
table.reloadData()
}
}
Second View Controller:
import UIKit
class SecondViewController: UIViewController {
@IBOutlet weak var input: UITextField!
@IBAction func addItem(_ sender: Any) {
print(input.text!)
var items:[String]
let itemsObject = UserDefaults.standard.object(forKey: "items")
if let tempItems = itemsObject as? [String] {
items = tempItems
items.append(input.text!)
} else {
items = [input.text!]
}
UserDefaults.standard.set(items, forKey: "items")
input.text = ""
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
table.reloadData()being called when you think it should be? If so, isitemsat that moment what you think it should be? If so, are the table view data source methods being called, and are they behaving correctly? You have a wonderful debugger at your fingertips. Debug!UITableViewDelegateandUITableViewDataSourcedo.