Faisal Faisal -4 years ago 120
Swift Question

NSUserDefaults in swift for saving Array of String for TableView

Hi I have a

and this is my code in

var itemList = [String]()

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

let name = AddNewItemViewController.itemName

if name == "" {

else {

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
I was trying some ways but it didn't work for me.

Answer Source

You can set itemList Array like this way.

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

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] {

Or you can also use stringArrayForKey.

if let items = defaults.stringArrayForKey("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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download