How to append entry to userdefualt

My code right now saves the label that displays a tuple. The problem is that if I changed view controllers and return to this view controller and enter a new entry all of the prior data is deleted. Everything works fine if I don’t have to switch view controllers and this is a one page application but my app requires switching of vcs. Someone suggested using UserDefaults.standard.removePersistentDomain but I am not trying to over write the vc when I return from another vc I just want to append to the user defualt that is already there.

               @IBAction func submitText(_ sender: Any) {

    llble.text = String(describing: result) + "\n"
                UserDefaults.standard.set(llble.text, forKey: "name")
    }

override func viewDidAppear(_ animated: Bool) {
    let save : String? = UserDefaults.standard.object(forKey: "name") as? String
    if let nameToDisplay = save {
        llble.text = nameToDisplay
    }}

hi Timswift,

You might want to have a detailed look at the Apple Developer Documentation on the lifecycle of a ViewController which is found at https://developer.apple.com/documentation/uikit/uiviewcontroller

This will help you to understand the various events like viewDidLoad, viewDidAppear, etc

The second part of your question, it is not very clear on what you want to do, but I believe you are trying to save the result to user defaults by appending it everytime. There are a couple of things you must note here,

  1. There is a limit on the size of the string you can save in User Defaults
  2. You can keep appending the data but soon some of the initial data might get redundant or irrelevant.
  3. If you want to save and log the data, a text file could be a better option for that

Lastly, how do you achieve that,

// Get the data from userDefaults
func loadString() -> String {
    return UserDefaults.standard.object(forKey: "name")  ?? ""
}

// Save the Data to UserDefaults
func saveString(string: String) {
    var existing = loadString() + "\n" + string
    UserDefaults.standard.set(existing, forKey: "name")
    UserDefaults.standard.synchronize()
}

Now in your submitText function, you can simply call it as

@IBAction func submitText(_ sender: Any) {
    let theText = String(describing: result)
    saveString(theText)
    llble.text = theText
}

override func viewDidAppear(_ animated: Bool) {
    let theText = loadString()
    llble.text = theText
    super.viewDidAppear(animated: animated)
}

cheers,

Jayant

This topic was automatically closed after 166 days. New replies are no longer allowed.