我有一个NSManagedObject子类,其中有一个dateOfBirth字段。

@NSManaged var dateOfBirth: NSDate

在其他地方,我下载了大量JSON字符串,我需要用下载的JSON版本填充dateOfBirth字段。我以为我已经计算好了,但后来当我使用这个值时,它是wsa nil,即使从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

有人知道为什么我的生日不能保存吗?
编辑:我得到的输出是:
 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

最佳答案

dateFormatNSDateFormatter)的yyyy-MM-dd'T'HH:mm:ss.SSS与得到的字符串不匹配。
您需要删除多余的1995-01-01T00:00:00=>.SSS才能进行匹配。

07-24 09:43
查看更多