Good, therefore, since you said that you want to save data over the launch of applications, you will need custom default settings for storing your goods. Since Dan already suggested that you basically do it right. You just want to set a variable that was not previously declared. But I will show you this in the following code. I will also take a second approach in which the elements are passed to the next view controller at runtime.
First example: imagine that we have two view controllers, for example, in your example. The first view controller contains a UITextField for entering custom text. Whenever we switch from the first view controller to the second view controller using the storyboard layout (for example, when a button is pressed), we take the existing texts from the previous sections from the user settings by default and add the current user input and then save it back to user defaults. This happens in the first view controller:
class ViewController: UIViewController { @IBOutlet weak var textField: UITextField! override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) if segue.identifier == "toSecondViewController" { let itemsFromDefaults = UserDefaults.standard.object(forKey: "items") var items: [String] if let tempItems = itemsFromDefaults as? [String] { items = tempItems items.append(textField.text!) } else { items = [textField.text!] } print(items) UserDefaults.standard.set(items, forKey: "items") } } }
This first controller looks very similar to your code, but I would like to add it for completeness.
Then, in the second view controller, we simply grab the elements from user defaults and store them directly in the instance variable of this view controller. With this, we can do what we want in other methods in the view controller and process the elements further. Since I said that you were missing, there was an instance variable declaration for storing items.
class ViewController2: UIViewController { private var items: [String]?
Second example: you can also declare an internal / public variable in ViewController2 so that you can set it directly from the first view controller to execute segue. Than you will not need to capture elements from the user defaults in ViewController2. To do this, you can access the segue destination view controller, and then transfer it to ViewController2 and directly set its elements.
class ViewController: UIViewController { @IBOutlet weak var textField: UITextField! override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) if segue.identifier == "toSecondViewController" { let itemsFromDefaults = UserDefaults.standard.object(forKey: "items") var items: [String]
I really hope that I can help you with this and explained it clearly. Feel free to leave a comment if you have any questions.