mayijia66fly
mayijia66fly

Reputation: 75

Adding things to NSUserDefaults - multiple views

I am creating a dictionary-like app and I want to store the user's search history using NSUserDefaults. I created a seaechHistory array outside the class. Now I am appending the searchHistory array and save it using NSUserDefaults in willSelectRowAtIndexPath, and I retrieve the stored history in a history view. The storage worked fine but when I re-run the app the NSUserDefaults set the seachHistory to the empty array and thus I lost all the saved data. The synchronize() method does work anywhere.

Initial View Controller:

 import UIKit

var searchHistory = [String]()


class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {


    @IBOutlet weak var tableView: UITableView!
    @IBOutlet var textField: UITextField!

    @IBAction func textFieldDidChange(sender: AnyObject) {
        tableView.hidden = false
        searchManager.updateFilter(textField.text)
        tableView.reloadData()
    }

    @IBAction func tapOnTextField(sender: AnyObject) {

        let textFieldLength = count(textField.text)

        if textFieldLength == 0 {
            tableView.hidden = true

        } else {
        tableView.hidden = false
        }
    }


    override func viewDidLoad() {

        super.viewDidLoad()

        textField.backgroundColor = UIColor.whiteColor()

        tableView.hidden = true

        self.textField.delegate = self

    }


    var searchManager = SearchManager()


    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return searchManager.filteredURLCount()
    }


    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")

        cell.textLabel!.text = searchManager.filteredURLAtIndex(indexPath.row)

        return cell
    }


    func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
        self.textField.text = searchManager.filteredURLAtIndex(indexPath.row)

        searchHistory.append(textField.text)

        NSUserDefaults.standardUserDefaults().setObject(searchHistory, forKey: "History")

        self.performSegueWithIdentifier("cellTapped", sender: "Cell")

        textField.text = nil
        tableView.hidden = true
        textField.resignFirstResponder()

        return indexPath
    }


    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        self.view.endEditing(true)
        self.tableView.hidden = true
    }

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }


    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "cellTapped" {
        var DestViewController: definitionView = segue.destinationViewController as! definitionView
        DestViewController.searchWord = textField.text
        } 
    }


}

History View Controller:

    import UIKit

class historyView: UIViewController {


    override func viewDidLoad() {
        super.viewDidLoad()

        searchHistory  = NSUserDefaults.standardUserDefaults().objectForKey("History")! as! [String]
        println(searchHistory)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        var destination: ViewController = segue.destinationViewController as! ViewController

    }

}

Upvotes: 0

Views: 166

Answers (1)

mkz
mkz

Reputation: 2302

You can read your array in viewDidLoad() method, then it won't be empty.

Add tihs code in your ViewController:

override func viewDidLoad() {
    super.viewDidLoad()
    searchHistory = NSUserDefaults.standardUserDefaults().objectForKey("History")! as! [String]
}

It should work.

Upvotes: 0

Related Questions