Alamofire, Objectmapper, Realm: Nested Objects

前端 未结 4 1293
梦谈多话
梦谈多话 2021-01-13 05:16

I\'m using Alamofire, Objectmapper, Realm and everything is working beside one thing: I can\'t map nested objects.

class Voting: Object, Mappable {

    dyna         


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-13 05:44

    The old ListTransform solution no longer works in Swift 3.

    This is what I'm using now; put this in a file called, ListExtensions.swift, for example.

    import Foundation
    import ObjectMapper
    import RealmSwift
    
    /// Maps object of Realm's List type
    func <- (left: List, right: Map)
    {
        var array: [T]?
    
        if right.mappingType == .toJSON {
            array = Array(left)
        }
    
        array <- right
    
        if right.mappingType == .fromJSON {
            if let theArray = array {
                left.append(objectsIn: theArray)
            }
        }
    }
    

    This allows you to simply use it like this:

    class Parent: Object, Mappable {
        dynamic var id: Int = 0
        var children = List()
    
        required convenience init?(_ map: Map) {
            self.init()
        }
    
        func mapping(map: Map) {
            id <- map["id"]
            children <- map["children"]
        }
    }
    

提交回复
热议问题