Faisal Faisal - 3 months ago 14
Swift Question

NSUserDefaults in swift for saving Array of String for TableView

Hi I have a

tableview
and this is my code in
MyItemTableViewController
Class

var itemList = [String]()

@IBAction func saveItemToList (segue: UIStoryboardSegue) {
let AddNewItemViewController = segue.sourceViewController as! addItemTableViewController

let name = AddNewItemViewController.itemName

if name == "" {

}
else {
itemList.append(name!)

let indexToInsert = itemList.count == 0 ? 0 : itemList.count - 1

let indexPath = NSIndexPath(forRow: indexToInsert, inSection: 0)

tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}

}


How can I save my array using
NSUserDefaults
I was trying some ways but it didn't work for me.

Answer

You can set itemList Array like this way.

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(itemList, forKey: "items")
defaults.synchronize()

When you need to extract from NSUserDefaults you can extract it like this

let defaults = NSUserDefaults.standardUserDefaults()
if let items = defaults.objectForKey("items") as? [String] {
    print(items)
}

Or you can also use stringArrayForKey.

if let items = defaults.stringArrayForKey("items") {
    print(items)
}

For more detail about NSUserDefaults read this tutorial

Edit: The problem is you are trying to add [String] object inside Sting array, that not possible, if you want to merge two array then write like this.

if let items = defaults.stringArrayForKey("items") {
    self.itemList = self.itemList + items
}