2015-09-04 14 views
0

我有一個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 
+0

'println(「dateOfBirth?:\(dateOfBirth)」)'它顯示了什麼?你似乎沒有使用'formatter'。 – Larme

+0

啊,我使用的格式化程序,但在我試圖找出發生了什麼事情,我刪除了它....我會更新問題與一些輸出掛起。 – dyatesupnorth

+0

從'dateFormat'中刪除'.SSS'' – Larme

回答

2

NSDateFormatteryyyy-MM-dd'T'HH:mm:ss.SSS)的dateFormat不匹配你1995-01-01T00:00:00字符串。

您需要刪除額外的.SSS =>yyyy-MM-dd'T'HH:mm:ss以匹配。

+0

除非它不匹配字符串1995-01-01T00:00:00.001例如。你真正需要做的是有兩個NSDateFormatters並嘗試它們兩個。然後給NSDictionary添加一個類別,從JSON字典中讀取一個日期,除非你喜歡在整個地方複製相同的代碼。 – gnasher729

0

if語句表達式總是返回false嗎?

object["json"]["dateOfBirth"].stringValue as? NSDate 

您正在獲取一個字符串,然後嘗試將其轉換爲NSDate。肯定會永遠失敗。

在其他範例你串專門解析到一個日期,當你把它

+0

如果您閱讀我的評論,我提到這是從最新的嘗試讓它工作,下面的例子,如果讓createdDate = object [「createdDate」]。string是我的dateOfBirth最初是如何 – dyatesupnorth

+0

看起來像你解析ISO 8601日期倍。我實際上正在搞亂我自己(儘管我的問題現在在Java中)。令人煩惱的是,似乎很少有解析器的實現可以與它們的所有排列組合使用。並且您的特定格式化字符串具有時間戳不包含的可選毫秒部分。我建議你尋找能夠處理整個格式的東西,如果你不控制數據的來源 – Kristoffer

相關問題