如何使用RKObjectMapping在嵌套的RLMObject中设置相同的主键?

时间:2015-10-07 11:48:10

标签: swift restkit realm

我想在嵌套的RLMObject中设置相同的主键 如何使用RKObjectMapping设置相同的ID?

首先,我制作了以下json文件 JSON文件

{
  "id": 1
  "obj2": {
    "name": "name1"  
  } 
}

其次,我制作了以下swift类文件 班级文件

class Obj2: RLMObject {
    dynamic var id: Int <-- I want to set same id as Obj1.id
    dynamic var name: String!

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

    class func responseMapping() -> RKObjectMapping {
        let objectMapping = RKObjectMapping(forClass: self)
        objectMapping.addAttributeMappingsFromDictionary([
            "name": "name"
        return objectMapping
    }
}

class Obj1: RLMObject {
    dynamic var id: Int!
    dynamic var obj2: Obj2?

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

    class func responseMapping() -> RKObjectMapping {
        let objectMapping = RKObjectMapping(forClass: self)
        objectMapping.addAttributeMappingsFromDictionary([
            "id": "id"

        objectMapping.addPropertyMappingsFromArray([
            RKRelationshipMapping(fromKeyPath: "obj2", toKeyPath: "obj2", withMapping: Obj2.responseMapping())
        ])

        return objectMapping
    }
}

1 个答案:

答案 0 :(得分:1)

您需要在相同的JSON基础对象上设置映射,而不是遍历范围,这将使映射依赖于关系。

class Obj2: RLMObject {
    dynamic var id: Int
    dynamic var name: String!

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

    class func responseMappingForBeingOwnedByObj1() -> RKObjectMapping {
        let objectMapping = RKObjectMapping(forClass: self)
        objectMapping.addAttributeMappingsFromDictionary([
            "id": "id",
            "name": "obj2.name"
        ])
        return objectMapping
    }
}

class Obj1: RLMObject {
    dynamic var id: Int!
    dynamic var obj2: Obj2?

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

    class func responseMapping() -> RKObjectMapping {
        let objectMapping = RKObjectMapping(forClass: self)
        objectMapping.addAttributeMappingsFromDictionary([
            "id": "id"
        ])

        objectMapping.addPropertyMappingsFromArray([
            RKRelationshipMapping(fromKeyPath: ".", toKeyPath: "obj2", withMapping: Obj2.responseMappingForBeingOwnedByObj1())
        ])

        return objectMapping
    }
}

警告的最后一句话:RestKit此时并不真正支持Realm。因此,现在使用其他东西可能会更好,例如Realm对解码对象表示的有限内置支持,Realm+JSONDecodable