wvteijlingen / Spine

A Swift library for working with JSON:API APIs. It supports mapping to custom model classes, fetching, advanced querying, linking and persisting.
MIT License
264 stars 109 forks source link

NSUnknownKeyException when trying to serialize Boolean attributes #139

Closed grahammccarthy closed 7 years ago

grahammccarthy commented 7 years ago

I get a very consistent error when trying to capture Boolean attributes in my Resource

All of my boolean attributes from the API start with 'is-'.

I've tried to use BooleanAttribute(), and Attribute() and both return the same error. I've also tried to store the value as String, Int, Bool.

I'm on the latest version of Spine.

ERROR:

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<APP.Item 0x60800019eb90> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key isRead.'

Example GET /items/2

{
  "data": {
    "type": "items",
    "id": "2",
    "attributes": {
      "title": "This is the title of my item",
      "body": "This is a body of my item",
      "is-discussed": false,
      "is-read": true,
      "created-at": "2016-11-24 22:07:07",
      "updated-at": "2016-11-24 22:07:07"
    },
    "links": {
      "self": "https://myappurl.com/items/2"
    }
  }
}

MY RESOURCE MODEL:

import Foundation
import Spine

class Item: Resource {

    var type : String?
    var title : String?
    //var isDiscussed : Bool?
    var isRead : Bool?
    var createdAt : Date?
    var updatedAt : Date?
    var author : User?

    override class var resourceType: ResourceType {
        return "items"
    }

    override class var fields: [Field] {
        return fieldsFromDictionary([
            "type": Attribute(),
            "title": Attribute(),
            //"isDiscussed": BooleanAttribute().serializeAs("is-discussed"),
            "isRead": BooleanAttribute().serializeAs("is-read"),
            "createdAt": DateAttribute(format:DATE_API_FORMAT).serializeAs("created-at"),
            "updatedAt": DateAttribute(format:DATE_API_FORMAT).serializeAs("updated-at"),
            "author": ToOneRelationship(User.self)
        ])
    }
}

Any help would be greatly appreciated!

Thanks, Graham.

wvteijlingen commented 7 years ago

Can you make isRead an NSNumber? Spine uses Key Value Coding, which unfortunately only works with reference types.

grahammccarthy commented 7 years ago

Thanks! That worked like a charm!