gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:11:10 24 4
gpt4 key购买 nike

我想在嵌套的 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
}
}

最佳答案

您需要在同一个 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 .

关于swift - 如何使用 RKObjectMapping 在嵌套 RLMObject 中设置相同的主键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32991411/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com