store array in userdefaults swift

The solution for “store array in userdefaults swift” can be found here. The following code will assist you in solving the problem.

var defaults = UserDefaults.standard
var itemArray = [“Find Mike”, “Buy Eggs”,”Buy Apple”]

override func viewDidLoad() {

super.viewDidLoad()
//First Way

if let items = defaults.array(forKey: “TodoListArray”) as? [String] {
itemArray = items
}
// Second Way
// itemArray = defaults.stringArray(forKey: “TodoListArray”) ?? []

}

@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {

var addedItems = UITextField()

let alert = UIAlertController(title: “Add New Item”, message: “”, preferredStyle: .alert)

let action = UIAlertAction(title: “Add Item”, style: .default) { action in
//What to do when user pressed the (Add Item)
self.itemArray.append(addedItems.text!)
self.defaults.set(self.itemArray, forKey: “TodoListArray”)
self.tableView.reloadData()
}

Thank you for using DeclareCode; We hope you were able to resolve the issue.

More questions on [categories-list]

0
inline scripts encapsulated in