0

My code below uses a struct to organize the data. However when I go to the next view controller and return to the original one all of the data is deleted. How can I use user defaults to save the data to the label.

             import UIKit
class ViewController: UIViewController {
@IBOutlet var c: UITextField!
@IBOutlet var a: UITextField!
@IBOutlet var label: UILabel!
var contacts = [Person]()

@IBAction func save(_ sender: Any) {
    contacts.append(Person(name: a.text!,  phone: Int(c.text!)!))
    let sortedContacts = contacts.sorted {
        ($0.name, $0.phone) < ($1.name, $1.phone)
    }
    label.text = contacts.count == 0 ? "" : sortedContacts.map {$0.description}.joined(separator: "\n")}

struct Person {
    var name: String
    var phone: Int

    var description: String {
        return   "\(name),\(phone)"
    }}}
  • 1
    Don’t use userdefaults to pass values between objects. Don’t use userdefaults to persist large amounts of data. Don’t use all of that force unwrapping. How are you navigating between view controllers? – Paulw11 Oct 13 '17 at 23:08
  • I am just using the basic segue button via storyboard to navigate between vcs. All I want to do is have whatever is on the label in vc 1 to be there if I go from v1 to vc2 to back to vc1. –  Oct 13 '17 at 23:37
  • You should use `prepareForSegue` to pass values. Make sure that you are using an unwind segue to go back, not another “forward” segue. – Paulw11 Oct 14 '17 at 00:02
  • I am not trying to pass data. The problem is the data is not being saved to the original vc. I just want to save data to the vc. @Paulw11 –  Oct 14 '17 at 00:05
  • You are trying to pass data. You don’t “save data to a vc”. If you want to persist data between runs of your app, then you should look at Core Data. To share data between objects in memory while your app is running you pas values between those objects. – Paulw11 Oct 14 '17 at 00:27

0 Answers0