Save last datePicker selection

2019-07-07 18:53发布

问题:

I have a project with an UIDatePicker.

I want that if I change my UIDatePicker value, for example at 9:23, when I restart my app value is still 9:23 and not the default value. How can I do that?

Here is my code:

@IBOutlet var myDatePicker: UIDatePicker!
var datePicker = /* Get Your Date Picker from somewhere */

// Store value using User Defaults
let currentDate = datePicker.date
NSUserDefaults.standardUserDefaults().setObject(currentDate, forKey: "Current-Date")

// Retrieve Value using User Defaults
if let date = NSUserDefaults.standardUserDefaults().objectForKey("Current- Date") as? NSDate {
   datePicker.setDate(date, animated: true)
}

I tried with standard userDefaults method but not worked.

回答1:

Hi I prepared for you some snipped code:

     import UIKit

        class ViewController: UIViewController {

// I have declared const key property to avoid mistakes (typo)
            let dateKey = "Current-Date"

            @IBOutlet weak var datePicker: UIDatePicker!
            override func viewDidLoad() {
                super.viewDidLoad()
            }

            override func viewDidAppear(animated: Bool) {
                super.viewDidAppear(animated)

    // This line load previous state when view controller did appear
                loadDate(true)
            }

            @IBAction func savePickerData(sender: AnyObject) {
                // When user taps into 'savePickerData' button picker state is saved
                saveDate()
            }

            func saveDate() {
                NSUserDefaults.standardUserDefaults().setObject(datePicker.date, forKey:dateKey)
            }

            func loadDate(animation: Bool) {
                guard let loadedDate = NSUserDefaults.standardUserDefaults().objectForKey(dateKey) as? NSDate else { return }

                datePicker.setDate(loadedDate, animated: animation)
            }

        }

Should works fine :)



回答2:

Your key is not the same "Current-Date" != "Current- Date". That is why it is not working :

    NSUserDefaults.standardUserDefaults().setObject(currentDate, forKey: "Current-Date")
...
    if let date = NSUserDefaults.standardUserDefaults().objectForKey("Current- Date") as? NSDate {

Use a constant to avoid this error:

let keyData = "Current-Date"
    NSUserDefaults.standardUserDefaults().setObject(currentDate, forKey: keyData)
...
    if let date = NSUserDefaults.standardUserDefaults().objectForKey(keyData) as? NSDate {