保存上次datePicker选择

时间:2015-12-14 22:15:02

标签: ios swift nsuserdefaults uidatepicker

我有一个UIDatePicker的项目。

我希望如果我更改UIDatePicker值,例如在9:23,当我重新启动时,我的应用值仍然是9:23,而不是默认值。我怎样才能做到这一点?

这是我的代码:

@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)
}

我尝试使用标准userDefaults方法,但没有效果。

2 个答案:

答案 0 :(得分:4)

您好我为您准备了一些剪切代码:

     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)
            }

        }

应该可行。)

答案 1 :(得分:3)

您的密钥不一样"当前日期" !="当前日期" 。这就是它不起作用的原因:

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

使用常量来避免此错误:

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