0

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.

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

8 Comments

Im trying to append items to itemList but it said Cannot convert value of type '[String]?' to expected argument type 'String' i don't no what i should do
i have another quotation if you don't mind , if i clicked on particular cell , i need the title of that cell be the header of the second view controller
Welcome mate, Happy coding :)
Can you add the new Post with you navigation code that will help me to understand what you have try.
Don't understand what you want, also there is no code of navigation, It is batter if you add new post.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.