4

I have an JSON-API that returns me arrays of Courses. The Courses have CourseLocations, CourseTypes etc. All of them have primary keys. I thought it would be great to parse everything using Codable and to update it using Realm().add(_:update:).

Everything works great. The problem comes when the API doesn't return a complete object.

Let's say. API "/types" returns me the array below, and it has all necessary data to create or update the object.

[
   { "id": "1", "name": "Type 1", "sessions": 10, "sessionTime": 120.0 },
   { "id": "2", "name": "Type 2", "sessions": 5, "sessionTime": 20.0 }
]

But then I call another API method "/courses", that returns me a course info plus the object "types" but not all, just its id and name:

[
   {
     "id": "0013",
     "name": "Super cool course",
     "type": { "id": "2", "name": "Type 2" }
    }
]

So, when I do "add(_:update:)" for a course I actually updating all values of my CourseType object, not just the name. As a result, my sessions and sessionTime properties are set to 0.

How do I avoid it?

Here is a class for a reference.

class CourseType: Object, Decodable {
    @objc dynamic var identifier = UUID().uuidString
    @objc dynamic var name = ""
    @objc dynamic var sessions = 0
    @objc dynamic var sessionTime = 0.0

    private enum CodingKeys: String, CodingKey {
        case identifier = "id"
        case name
        case sessions
        case sessionTime = "session_time"
    }

    override static func primaryKey() -> String {
        return "identifier"
    }
}
Jarod
  • 485
  • 5
  • 16

0 Answers0