Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

Save data of a Label in swift

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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...