I have decodes JSON value into object. The object looks as expected, but when I try to access it's property.
let jsonData = try JSONSerialization.data(withJSONObject: JSON, options: [])
let decoder = JSONDecoder()
let doctor = try! decoder.decode(Doctor.self, from: jsonData)
let txt = "\(doctor.title). \(doctor.firstName) \(doctor.lastName)" // Runtime crash: (Thread 1: EXC_BAD_ACCESS (code=1, address=0x40))
Runtime crash: (Thread 1: EXC_BAD_ACCESS (code=1, address=0x40))
Class Person:
import UIKit
class Person: Codable {
let firstName: String
let lastName: String
let imageURL: URL
private enum CodingKeys: String, CodingKey {
case firstName
case lastName
case imageURL = "profileImgPath"
}
init(firstName: String, lastName: String, imageURL:URL) {
self.firstName = firstName
self.lastName = lastName
self.imageURL = imageURL
}
}
Class Doctor:
import UIKit
class Doctor: Person {
var title: String
private enum CodingKeys: String, CodingKey {
case title
}
init(firstName: String, lastName: String, imageURL:URL, title: String) {
self.title = title
super.init(firstName: firstName, lastName: lastName, imageURL: imageURL)
}
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.title = try values.decode(String.self, forKey: .title)
try super.init(from: decoder)
}
}
from Crash when accessing Object properties after decoding from JSON

No comments:
Post a Comment