2016-03-06 12 views
0

我試圖挽救[NSDate: Double]類型的字典到PFUser.currentUser's記錄:保存Dicitionary與NSDate的()爲Parse.com關鍵失敗

let user = PFUser.currentUser()! 
let date = NSDate() 
user["savedDictionary"] = [date: 1.0] // error, see below. ["test": 1.0] works though 

user.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in 
    if error == nil { 
     print("Dictionary uploaded!") 
    } else { 
     print(error) 
    } 
} 

的錯誤,我得到:

Caught "NSInvalidArgumentException" with reason "Invalid (non-string) key in JSON dictionary": 

此錯誤也導致PFUser.currentUser註銷。

+0

該錯誤消息似乎包括該問題的原因:一鍵應該是一個字符串 - 不是一個NSDate。 – Moritz

+0

因此,沒有辦法將NSDate保存爲解析字典時的關鍵字? – MJQZ1347

+0

不,根據JSON規範,所有的鍵都必須是字符串,並且您也不能將'NSDate'對象保存爲值。解決方法是創建相對於UNIX或Cocoa引用日期的時間間隔並使用其字符串表示形式。在目的地上將時間間隔轉換回日期。 – vadian

回答

1

轉換日期鍵爲字符串:

let date = NSDate() 
let df = NSDateFormatter() 

// set a format. just an example 
// 2012-01-04T08:21:04.674+02:00 
df.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSSZZZZZ" 


let str = df.stringFromDate(date) 
assert(str != nil) 

myDict[str] = value