我通過RESTFUL API獲取JSON對象並插入到核心數據實體中。Swift - 從字符串錯誤日期
一個這樣的實體是約會,這是我的實體屬性
extension Appointment {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Appointment> {
return NSFetchRequest<Appointment>(entityName: "Appointment");
}
@NSManaged public var date: Date?
@NSManaged public var id: Int32
@NSManaged public var message: String?
@NSManaged public var patient_name: String?
@NSManaged public var doctor: Doctor?
}
這裏是我使用插入實體
for(_,jsonData):(String, JSON) in self.data["appointment"]["list"] {
// Construct appointment date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
let appointmentDate = dateFormatter.date(from: jsonData["date"].string!)!
print(appointmentDate)
// Preare appointment entity for inserting
let appointment = NSEntityDescription.insertNewObject(forEntityName: "Appointment", into: moc)
appointment.setValue(jsonData["id"].int32, forKey: "id")
appointment.setValue(appointmentDate, forKey: "date")
appointment.setValue(jsonData["message"].int32, forKey: "message")
appointment.setValue(jsonData["patient_name"].int32, forKey: "patient_name")
do {
try moc.save()
} catch {
fatalError("\(error)")
}
}
而且這裏的代碼相關的JSON我從一開始API
"appointment": {
"list": {
"id": 1,
"date": "2017-07-03 17:30",
"message": "Some message is usefule here",
"patient_name": "John Doe",
"doctor_id": 4
}
}
但是當我運行代碼時,出現以下錯誤:
fatal error: unexpectedly found nil while unwrapping an Optional value
代碼有什麼問題?
謝謝。
嘗試設置區域設置你的' dateFormatter'在調用'date()'之前 –
與此處相同的問題:https://stackoverflow.com/questions/40692378/dateformatter-doesnt-return-date-for-hhmmss? –
我認爲問題在於讓appointmentDate = dateFormatter.date(來自:jsonData [「date」]。string!你正在添加!它可能是nil。你確定你的json響應的每個json對象都有日期嗎? –