通过单击按钮将当前日期保存到 NSUserDefaults
Save current date via button click into NSUserDefaults
我一直在尝试通过单击 NSUserDefaults 按钮将当前日期保存在 iPhone 上,但它不起作用。我真的不知道如何获取当前日期,将其保存为 var 并在函数中调用它。但我试过了:
@IBAction func saveButtonTapped (sender:AnyObject){
var date = NSDate()
var userDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()
var timeList:NSMutableArray? = userDefaults.objectForKey("timeList") as? NSMutableArray
var dataSet:NSMutableDictionary = NSMutableDictionary()
dataSet.setObject(date, forKey: "time")
if ((timeList) != nil){
var newMutableList:NSMutableArray = NSMutableArray();
for dict:AnyObject in timeList!{
newMutableList.addObject(dict as NSDictionary)
}
userDefaults.removeObjectForKey("timeList")
newMutableList.addObject(dataSet)
userDefaults.setObject(newMutableList, forKey: "timeList")
}else{
userDefaults.removeObjectForKey("timeList")
timeList = NSMutableArray()
timeList!.addObject(dataSet)
userDefaults.setObject(timeList, forKey: "timeList")
}
userDefaults.synchronize()
}
你可以试试这个。
@IBAction func saveButtonTapped (sender:AnyObject){
let userDefaults = NSUserDefaults.standardUserDefaults()
if var timeList = userDefaults.objectForKey("timeList") as? [NSDate]
{
timeList.append(NSDate())
userDefaults.setObject(timeList, forKey: "timeList")
}
else
{
userDefaults.setObject([NSDate()], forKey: "timeList")
}
userDefaults.synchronize()
}
回读列表
if let timeList = NSUserDefaults.standardUserDefaults().objectForKey("timeList") as? [NSDate]
{
println(timeList)
}
我一直在尝试通过单击 NSUserDefaults 按钮将当前日期保存在 iPhone 上,但它不起作用。我真的不知道如何获取当前日期,将其保存为 var 并在函数中调用它。但我试过了:
@IBAction func saveButtonTapped (sender:AnyObject){
var date = NSDate()
var userDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()
var timeList:NSMutableArray? = userDefaults.objectForKey("timeList") as? NSMutableArray
var dataSet:NSMutableDictionary = NSMutableDictionary()
dataSet.setObject(date, forKey: "time")
if ((timeList) != nil){
var newMutableList:NSMutableArray = NSMutableArray();
for dict:AnyObject in timeList!{
newMutableList.addObject(dict as NSDictionary)
}
userDefaults.removeObjectForKey("timeList")
newMutableList.addObject(dataSet)
userDefaults.setObject(newMutableList, forKey: "timeList")
}else{
userDefaults.removeObjectForKey("timeList")
timeList = NSMutableArray()
timeList!.addObject(dataSet)
userDefaults.setObject(timeList, forKey: "timeList")
}
userDefaults.synchronize()
}
你可以试试这个。
@IBAction func saveButtonTapped (sender:AnyObject){
let userDefaults = NSUserDefaults.standardUserDefaults()
if var timeList = userDefaults.objectForKey("timeList") as? [NSDate]
{
timeList.append(NSDate())
userDefaults.setObject(timeList, forKey: "timeList")
}
else
{
userDefaults.setObject([NSDate()], forKey: "timeList")
}
userDefaults.synchronize()
}
回读列表
if let timeList = NSUserDefaults.standardUserDefaults().objectForKey("timeList") as? [NSDate]
{
println(timeList)
}