0

I have a TextField in my settingsController that i can modify selecting a name from a pickerView, the problem is this : when i change the text of my textField i also change the text of a label in another controller, it work but when i close and reopen my app the label is empty, i can't find a way to save the text that i give it with the pickerView.

My code in the settingsController

override func viewDidLoad() {
        super.viewDidLoad()


        var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

        if let firstNameIsNotNill = defaults.objectForKey("firstName") as? String {
            self.currencyLabel.text = defaults.objectForKey("firstName") as String
        }

        currencyLabel.delegate = self
}

func currencyDoneClicked(sender: UIBarButtonItem) {

        var myRow = picker.selectedRowInComponent(0)
        currencyLabel.text = pickerData.objectAtIndex(myRow) as NSString
        DataManager.sharedInstance.contenitore = currencyLabel.text
var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
            defaults.setObject(self.currencyLabel.text, forKey: "firstName")
            defaults.synchronize()     
        }

DataManager :

import UIKit

class DataManager: NSObject {

    class var sharedInstance:DataManager {
        get {
            struct Static {
                static var instance : DataManager? = nil
                static var token : dispatch_once_t = 0
            }

            dispatch_once(&Static.token) { Static.instance = DataManager() }

            return Static.instance!
        }
    }

    var contenitore : String!
}

And in the other controller :

    override func viewDidLoad() {
        super.viewDidLoad()

        labelCurrency.text = DataManager.sharedInstance.contenitore
}
Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
Ludyem
  • 1,709
  • 1
  • 18
  • 33

1 Answers1

2

Just use NSUserDefaults.

NSUserDefaults.standardUserDefaults().setValue(textField.text, forKey: "savedTextField")

Then, when you start up again, populate the field in viewDidLoad or viewWillAppear.

if let text = NSUserDefaults.standardUserDefaults().stringForKey("savedTextField") {    
   textField.text = text
}
Mundi
  • 79,884
  • 17
  • 117
  • 140
  • it works to save the textField but if i use it in the label controller nothing happens the label is still empty... i think it's because there is : labelCurrency.text = DataManager.sharedInstance.contenitore that change my label again, but without this i can't modify my label when i change the text in the textField. what should i do? – Ludyem Oct 17 '14 at 15:12
  • That you should address in your data manager. If it returns nothing although it should, fix it. – Mundi Oct 17 '14 at 15:21