gpt4 book ai didi

json - 如何在 Swift 中使用 Mappable 协议(protocol)映射自定义对象的 Realm 列表

转载 作者:IT王子 更新时间:2023-10-29 05:48:08 30 4
gpt4 key购买 nike

在我的 Realm 对象模型中,我有一个名为“事件”的对象。每个事件都有一个事件位置列表。我正在尝试从 json 映射这些对象,但 EventLocations 列表始终为空。对象看起来像这样(为清楚起见进行了简化):

class Event: Object, Mappable {
override class func primaryKey() -> String? {
return "id"
}

dynamic var id = ""
var eventLocations:List<EventLocation> = List<EventLocation>()

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

class EventLocation: Object, Mappable {
override class func primaryKey() -> String? {
return "id"
}

dynamic var id: String = ""
dynamic var name: String = ""

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

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

我拥有的 json 是一个事件对象数组。它来自 Alamofire 响应,我这样映射它:

var events = Mapper<Event>().mapArray(json!)

json 格式如下:

[
{
"id" : "21dedd6d",
"eventLocations" : [
{
"name" : "hh",
"id" : "e18df48a",
},
{
"name" : "tt",
"fileId" : "be6116e",
}
]
},
{
"id" : "e694c885",
"eventLocations" : [
{
"name" : "hh",
"id" : "e18df48a",
},
{
"name" : "tt",
"fileId" : "be6116e",
}
]
}
]

有谁知道如何使用 Mappable 协议(protocol)映射自定义对象列表。为什么“eventLocations”列表总是空的?

最佳答案

看看one of the Issues page on ObjectMapper's GitHub repo , 似乎还没有正确支持 Realm List 对象。

该问题还列出了使其暂时可用的潜在解决方法,我将在此处反射(reflect):

class MyObject: Object, Mappable {
let tags = List<Tag>()

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

func mapping(map: Map) {
var tags: [Tag]?
tags <- map["tags"]
if let tags = tags {
for tag in tags {
self.tags.append(tag)
}
}
}
}

关于json - 如何在 Swift 中使用 Mappable 协议(protocol)映射自定义对象的 Realm 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38117173/

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