I'm a beginner who recently started studying Swift.
I'd like to save the value I set in DatePicker as NSDate type.
@IBAction func changed (sender:UIDatePicker) {
let date2 = datepicker1.date
let myDefault=NSUserDefaults.standardUserDefaults()
myDefault.setObject(date2,forKey:"date")
myDefault.synchronize()
}
Is the description like this correct?
Also, I would like to read out the saved values.
let userDefaults=NSUserDefaults.standardUserDefaults()
letdate2:NSDate=userDefaults.objectForKey("date")
even if it is described as
"Cannot convert the expression's type 'NSString' to type 'String'" error appears.
How can I save and read it?
swift
Why don't you convert it to timeIntervalSince1970 instead of NSDate, save it, and load it with [NSDate initEithTimeIntervalSince1970:]
That's the right way to save it.
The readout method is correct, but one thing is that the objectForKey
method is defined as returning the AnyObject?
type, so if you want to receive the return value in NSDate
, you need to cast (type conversion).
So,
let date2:NSDate=userDefaults.objectForKey("date") as NSDate
should be written as .
In this case, the variable type can be omitted and written as follows because type inference works:
let date2=userDefaults.objectForKey("date") as NSDate
Also, if you try to cast to NSDate type but the contents are incompatible with NSDate type, you get runtime errors, so if the cast fails, write if~let~as?
as follows:
iflet date2=userDefaults.objectForKey("date") as? NSDate {
println("date2:\(date2)")
}
In this case, if the value corresponding to the "date"
key is not of the NSDate
type, the date2
variable contains nil
instead of a runtime error.
© 2024 OneMinuteCode. All rights reserved.