如何使用Realm以正确的方式为这个json建模?

时间:2017-05-27 00:23:33

标签: ios iphone swift realm

这是我第一次使用Realm而我正在尝试对此JSON进行建模,我也在使用ObjectMapper       

  {
    companies: [
        {
             id: "1",
             name: "Quisque ut",
             logo: "0",
             company_categories: [
                "1",
                "2"
             ]
        }
    ],
    categories: [
        {
             id: "1",
             name: "Category1"
        },
        {
             id: "2",
             name: "Category2"
        },
        {
             id: "3",
             name: "Category3" 
        }
    ]
 }

在我的应用中,这是我正在实施的代码     

class Category: Object, Mappable {
    dynamic var id = ""
    dynamic var name = ""

    required convenience init?(map: Map) {
        self.init()
    }

    func mapping(map: Map) {
        id <- map["id"]
        name <- map["name"]
    }

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

我的对象公司是这样的:     

class Company: Object, Mappable {
    dynamic var id = ""
    dynamic var name = ""
    dynamic var logo = ""
    let categories = List<Category>()

    required convenience init?(map: Map) {
        self.init()
    }

    func mapping(map: Map) {
        id <- map["id"]
        name <- map["name"]
        logo <- map["logo"]

        var categories: [String]? = nil
        categories <- map["company_categories"]
        let realm = try! Realm()

        categories?.forEach { category in
            let categoryObject = realm.objects(Company.self).filter({ $0.id == category }).first
            self.categories.append(categoryObject!)
        }
    }

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

我得到了这样的错误:

  

由于未捕获的异常“RLMException”而终止应用程序,原因是:“无法添加来自不同领域的对象”

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,则需要使用TransformType来解释如何映射List

override func mapping(map: Map) {
    location <- map["location"]
    list <- (map["company_categories"], RealmListTransform<Category>())
}

这是我使用的扩展名

class RealmListTransform<T: Object>: TransformType where T: Mappable {

typealias Object = List<T>
typealias JSON = [[String: Any]]

let mapper = Mapper<T>()

func transformFromJSON(_ value: Any?) -> List<T>? {
    let result = List<T>()
    if let tempArr = value as? [Any] {
        for entry in tempArr {
            let mapper = Mapper<T>()
            let model: T = mapper.map(JSONObject: entry)!
            result.append(model)
        }
    }
    return result
}

func transformToJSON(_ value: Object?) -> JSON? {
    var results = [[String:Any]]()
    if let value = value {
        for obj in value {
            let json = mapper.toJSON(obj)
            results.append(json)
        }
    }
    return results
}

}