这是我的代码。我想在用户默认值中保存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")
}
答案 0 :(得分:1)
NSUserDefaults使用设备存储在应用程序运行之间保存数据。
在您的情况下,最简单的方法是保存两个不同的日期对象,或者您可以创建包含两个日期对象的字典并保存它。
存储
UserDefaults.standard.set(todayString, forKey: "todayStringKey")
提取
let RetrivedDate = UserDefaults.standard.object(forKey: "todayStringKey") as? NSDate
删除 - 如果您想从存储中完全删除它
UserDefaults.standard.removeObject(forKey: "todayStringKey")