So I have two viewControllers. One contains tableView to display data from an array. second viewController is used to add stuff in an array.
here is my viewController file:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var txtTitle: UITextField!
@IBOutlet weak var txtLocation: UITextField!
@IBOutlet weak var txtDate: UITextField!
@IBOutlet weak var txtTime: UITextField!
var eventsArray = [Event]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func btnSave() {
let newEvent = Event(eventTitle: txtTitle.text!, eventLocation: txtLocation.text!)
eventsArray.append(newEvent)
let savedEvents = NSKeyedArchiver.archivedData(withRootObject: eventsArray)
UserDefaults.standard.set(savedEvents, forKey: "savedEvents")
UserDefaults.standard.synchronize()
}
Here is my tableView:
import UIKit
class EventsTable: UIViewController, UITableViewDataSource, UITableViewDelegate{
//var tableData = ViewController()
var events = [Event]()
@IBOutlet weak var table: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return events.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomeCell
cell.title.text = events[indexPath.row].title
cell.location.text = events[indexPath.row].location
return cell
}
func retriveData(){
if let data = UserDefaults.standard.object(forKey: "savedEvents") as? Data {
if let storedData = NSKeyedUnarchiver.unarchiveObject(with: data) as? [Event]{
events = storedData
}
}
}
override func viewDidAppear(_ animated: Bool) {
retriveData()
table.reloadData()
}
}
Here is my UI: main.storyboard
Now, every time i add an event and go back to my tableView, it only shows the title in the cell even though i have custom cell set up (that's one of the issue). Other issue, the main one, is that if i go back to my viewController to add another event, it adds it BUT it overwrites the old array and it shows the latest event i added and replaces the old one and only shows the new event I added in the tableView. I have no clue what is going on here. I have a feeling that every time I hit "Save" button it creates a new array?
I have only implemented eventTitle and eventLocation so far.
Here is the link to my project if y'all having trouble understanding what i mean https://mega.nz/#!XBxU1Q5J!cAhpRrZJo7an4ab8HmD1HtH7GSisScKOGoykGm9orJo