JSONModel not working with Swift arrays

久未见 提交于 2019-12-01 08:07:49

问题


I am having some trouble using JSONModel in Swift.

I am trying to create a ToDo list app that would persist a collection of items so that the ToDo items are preserved when the app is closed. This is the code I use:

class ToDoItem: JSONModel {
    var name: String = ""
    var isCompleted: Bool = false
    var createdOn: NSDate = NSDate()
}

class ToDoList: JSONModel {
    var items: [ToDoItem] = []
}

I can convert a ToDoItem to JSON by calling toJSONString() but the same method doesn't work with ToDoList, it returns nil. Any idea why is this happening?


回答1:


JSONModel does not support Swift due to incompatibilities with the reflection supported by the Obj-C runtime. This reflection ability is currently required by JSONModel in order to resolve types correctly. We are looking into alternative methods of defining the type mappings though.

Specifically, JSONModel relies on the use of protocols to determine the type of items in collection types, such as dictionaries, arrays, etc. Protocols defined in Swift are not visible at runtime - preventing JSONModel from deserializing collection types correctly.

For the time being, you have two options:

  1. switch from JSONModel to another JSON (de)serialization library with support for Swift
  2. define your models in Objective-C

I know this isn't ideal, but I'm afraid a workaround is not possible with the current JSONModel behavior.



来源:https://stackoverflow.com/questions/24742628/jsonmodel-not-working-with-swift-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!