Reputation: 830
I have an NSManagedObject
Subclass that has a dateOfBirth
field in it.
@NSManaged var dateOfBirth: NSDate
Elsewhere, I am downloading a load of JSON strings and I need to fill my dateOfBirth
field with the downloaded JSON version. I thought I had this figured, but later when I went to use the value it wsa nil, even though the value I was getting returned from the JSON was there.
Since then I've tried all sorts of incantations to try and get the thing to save.
//This is my latest 'attempt', trying to downcast the value to NSDate, it fails, originally i was just getting the .string value and converting it to a date
if let dateOfBirth = object["json"]["dateOfBirth"].stringValue as? NSDate{
//I actually had this formatter near the top of the function but thought perhaps it wasn't saving because the formatter was inaccessible or something?
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
//This value returns correctly
println("dateOfBirth? : \(dateOfBirth)")
newSurveyObj.dateOfBirth = dateOfBirth
//This returns a nil for the dateOfBirth
println("newSurveyObj? : \(newSurveyObj.dateOfBirth)")
}
The weird thing is, I can store dates in a similar fashion elsewhere in the app,
for example this:
if let createdDate = object["createdDate"].string
{
newWorkObj.createdDate = formatter.dateFromString(createdDate)!
}
works, with this being its NSManagedObject
Sub Class:
@NSManaged var createdDate: NSDate
Does anybody have any ideas why my dateOfBirth wont save?
edit: The output I am getting for this:
if let dateOfBirth = object["json"]["dateOfBirth"].string{
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
println("dateOfBirth? : \(dateOfBirth)")
newEcoObj.dateOfBirth = formatter.dateFromString(dateOfBirth)!
println("newSurveyObj? : \(newSurveyObj.dateOfBirth)")
}
is this:
dateOfBirth? : 1995-01-01T00:00:00
fatal error: unexpectedly found nil while unwrapping an Optional value
However, when I declare the dateOfBirth as optional, I get this output:
dateOfBirth? : 1995-01-01T00:00:00
newSurveyObj? : nil for Street name
Upvotes: 0
Views: 343
Reputation: 26036
The dateFormat
of the NSDateFormatter
(yyyy-MM-dd'T'HH:mm:ss.SSS
) doesn't match string you get 1995-01-01T00:00:00
.
You need to remove the extra .SSS
=> yyyy-MM-dd'T'HH:mm:ss
to have a match.
Upvotes: 2
Reputation: 440
Wouldn't the if statement expression always return false?
object["json"]["dateOfBirth"].stringValue as? NSDate
You are specifically getting a string and then try to cast it to an NSDate. Pretty sure that will always fail.
In your other example you are specifically parsing the string to a date when you set it
Upvotes: 0