我正在通过 RESTFUL API 获取 JSON 对象并插入到核心数据实体中。
一个这样的实体是约会,这是我的实体属性
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)")
}
}
这是我从 API 获取的相关 JSON
"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
代码有什么问题?
谢谢。
最佳答案
在给定的代码中有两种可能的崩溃
let appointmentDate = dateFormatter.date(from: jsonData["date"].string!)!
在上一行中,如果日期值为 null 或使用不同的格式,它将崩溃
appointment.setValue(jsonData["message"].int32, forKey: "message")
这里它可能会崩溃,因为消息来自字符串,但您正在转换为 int32 并且在 Appointment 实体中它被视为字符串并且对于 patient_name 也是如此
请检查下面的更新代码
for(_,jsonData):(String, [String: Any]) in self.data["appointment"]["list"] {
// Construct appointment date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
var appointmentDate
if let date = jsonData["date"].string {
appointmentDate = dateFormatter.date(from: date) // possible crash may be date may be empty or or not given same date format which we used
}
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"], forKey: "message")// possible crash :: Here you are getting String converting to Int
appointment.setValue(jsonData["patient_name"].int32, forKey: "patient_name")
do {
try moc.save()
} catch {
fatalError("\(error)")
}
}
关于json - Swift - 来自字符串错误的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45189452/