Unbox + Realm native" List"宾语

时间:2017-01-25 12:33:14

标签: ios swift realm unbox

更新

  

最后Unbox库的作者回答了我的问题。   https://github.com/JohnSundell/Unbox/issues/156

我尝试使用Unbox使用RealmList对象与其他相关对象放在一起。来自服务器的JSON响应具有此结构。

[
  {
    "name": "bla bla",
    "desc": "bla bla",
    "sequential": true,
    "createdAt": "2017-01-23T09:58:05.095Z",
    "hmImages": [
      {
        "urlBase": "https://blabla.com",
        "fullresPath": "/blaPath/iyba783fR81L8y.jpg",
        "id": "bla bla"
      },
      {
        "urlBase": "https://blabla.com",
        "fullresPath": "/blaPath/iyba783fR81L8y.jpg",
        "id": "bla bla"
      }
    ],
    "tags": [],
    "id": "bla bla"
  },
  {
    "name": "bla bla",
    "desc": "bla bla",
    "sequential": true,
    "createdAt": "2017-01-23T09:58:05.095Z",
    "hmImages": [
      {
        "urlBase": "https://blabla.com",
        "fullresPath": "/blaPath/iyba783fR81L8y.jpg",
        "id": "bla bla"
      }
    ]
    "tags": [],
    "id": "bla bla"
  }
]

请注意,root对象是字典的Array。每个字典都有Array个图像字典。

Realm中保存对象的类看起来像这样:

// MARK: - Realm
final class Challenge: Object {

    dynamic var id = ""
    dynamic var name = ""
    dynamic var desc = ""
    dynamic var sequential = false
    dynamic var createdAt = Date()
    dynamic var btPlayground = ""

    // Relations
    let hmImages = List<Image>()
    let tags = List<Tag>()

    override static func primaryKey() -> String? {
        return "id"
    }

}

// MARK: - Unboxable
extension Challenge: Unboxable {

    convenience init(unboxer: Unboxer) throws {
        self.init()

        // Date formatter
        let dateFormatter = ISODateFormatter()

        id = try unboxer.unbox(key: "id")
        name = try unboxer.unbox(key: "name")
        desc = try unboxer.unbox(key: "desc")
        sequential = try unboxer.unbox(key: "sequential")
        createdAt = try unboxer.unbox(key: "createdAt", formatter: dateFormatter)
        btPlayground = try unboxer.unbox(key: "btPlayground")

    }

}

hmImages密钥路径出现问题。 Unbox无法自动解析,我需要一种方法来执行此操作。

我尝试了UnboxableByTransform这样的事情:

extension List<T>: UnboxableByTransform {

    public typealias UnboxRawValue = [[String:Any]]

    public static func transform(unboxedValue: Array<[UnboxableDictionary]>) -> List<T>? {


    }

}

但没有奏效。 有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:-1)

你只是以错误的方式做到这一点。对于json,请阅读here

如果你坚持自己的方式。你应该考虑到Realm不接受你在Any中使用的public typealias UnboxRawValue = [[String:Any]]类型,你只能使用Realm列出的类型。这是Bool,Int8,Int16,Int32,Int64,Double,Float,String,NSDate和NSData。