我有一個NSManagedObject
其中有dateOfBirth
字段的子類。Swift無法存儲JSON字符串作爲日期
@NSManaged var dateOfBirth: NSDate
在其他地方,我下載JSON字符串的負載,我需要填補我dateOfBirth
場與下載的JSON版本。我以爲我有這個想法,但後來當我去使用它的值爲零時,即使我從JSON返回的值在那裏。
從那時起,我嘗試了各種咒語試圖讓事情保存。
//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)")
}
奇怪的是,我可以存儲日期在應用程序的其他地方類似的方式,
例如這樣的:
if let createdDate = object["createdDate"].string
{
newWorkObj.createdDate = formatter.dateFromString(createdDate)!
}
作品,這個是它的NSManagedObject
子類:
@NSManaged var createdDate: NSDate
有沒有人有任何想法,爲什麼我的dateOfBirth不會保存?
編輯:輸出我得到這個:
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)")
}
是這樣的:
dateOfBirth? : 1995-01-01T00:00:00
fatal error: unexpectedly found nil while unwrapping an Optional value
然而,當我宣佈出生日期爲可選,我得到這樣的輸出:
dateOfBirth? : 1995-01-01T00:00:00
newSurveyObj? : nil for Street name
'println(「dateOfBirth?:\(dateOfBirth)」)'它顯示了什麼?你似乎沒有使用'formatter'。 – Larme
啊,我使用的格式化程序,但在我試圖找出發生了什麼事情,我刪除了它....我會更新問題與一些輸出掛起。 – dyatesupnorth
從'dateFormat'中刪除'.SSS'' – Larme