Save data of a Label in swift

时光毁灭记忆、已成空白 提交于 2020-01-06 20:54:34

问题


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
}

回答1:


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
}


来源:https://stackoverflow.com/questions/26424240/save-data-of-a-label-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!