Swift - 如何在默认情况下存储多个日期并检索它?

Swift - How to store multiple date in default and retrieve it?

这是我的代码。我想将 todayString 和 nextString 保存在用户默认值中,这样我就可以在不是星期二的时候在标签中显示存储的日期(每周二更新)。

let today = NSDate()
    let nextTue = Calendar.current.date(byAdding: .day, value: 6, to: today as Date)
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd"
    let todayString = formatter.string(from: today as Date)
    let nextString = formatter.string(from: nextTue!)
    formatter.dateFormat = "dd-MMM-yyyy"

    let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
    let components = calendar!.components([.weekday], from: today as Date)

    if components.weekday == 3 {
        print("Hello Tuesday")
        thisWeekDate.text! = "\(todayString) - \(nextString)"

    } else {
        print("It's not Tuesday")
    }

NSUserDefaults 使用设备存储在应用程序运行之间保存数据。

在您的情况下,最简单的方法是保存两个不同的日期对象,或者您可以创建一个包含两个日期对象的字典并将其保存。

商店

UserDefaults.standard.set(todayString, forKey: "todayStringKey")

检索

let RetrivedDate = UserDefaults.standard.object(forKey: "todayStringKey") as? NSDate

删除 - 如果您想从存储中完全删除它

UserDefaults.standard.removeObject(forKey: "todayStringKey")