Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR TYPESCRIPT

store array in userdefaults swift

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()
        }
 
PREVIOUS NEXT
Tagged: #store #array #userdefaults #swift
ADD COMMENT
Topic
Name
2+2 =