Adam Strike
Adam Strike

Reputation: 405

Trouble with storing an array permanently

I am trying to store tasks in an array permanently for a user in my basic checklist app for iOS (the task to be added to the checklist is entered into a UITextField) like this:

var list: [String] = [String]()

@IBOutlet weak var itemField: UITextField!

@IBAction func addItemPressed(sender: AnyObject) {

    let task: String? = itemField.text

    list?.append(task!)

    itemField.text = nil

    NSUserDefaults.standardUserDefaults().setObject(list, forKey: "list")

    let storedList = NSUserDefaults.standardUserDefaults().objectForKey("list")! as! NSArray

    print(storedList)

}

However when the stored array prints to the console it only contains the tasks entered from that instance of running the program.

For example if I enter: "Finish the dishes" into the textfield the array printed to the console will contain the text. However when I restart the program the array is empty.

My knowledge of NSUserdefaults is limited as I am mostly still a beginner therefore my logic is most likely just incorrect. I would greatly appreciate it if you know of a better way to store objects or would be able to correct me. Thanks in advance :)

Upvotes: 0

Views: 89

Answers (1)

vacawama
vacawama

Reputation: 154691

Your problem is that you aren't loading the stored list data into list at app startup. Then when addItemPressed is called, you store the item into the empty list and then overwrite whatever was stored in NSUserDefaults.

You need to load the stored data at app startup. You could do this is viewDidLoad:

list = NSUserDefaults.standardUserDefaults().objectForKey("list") as? [String] ?? []

This will load the previously stored value in NSUserDefaults into your list property or initialize it to an empty array if there is no such list stored in NSUserDefaults.

Upvotes: 3

Related Questions