gpt4 book ai didi

swift - Alamofire,对象映射器, Realm : Nested Objects

转载 作者:搜寻专家 更新时间:2023-10-31 08:16:43 24 4
gpt4 key购买 nike

我正在使用 Alamofire、Objectmapper、Realm,除此之外一切正常:我无法映射嵌套对象。

class Voting: Object, Mappable {

dynamic var votingID: String = ""
dynamic var question: String = ""
var votingOptions = List<VotingOption>()

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

func mapping(map: Map) {
votingID <- map["id"]
question <- map["question"]
votingOptions <- map["votingOptions"]
}

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

class VotingOption: Object, Mappable{

dynamic var optionID: String = ""
dynamic var text: String = ""


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

func mapping(map: Map) {
optionID <- map["id"]
text <- map["optionText"]
}

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

我要映射的 JSON 是:

{
"Voting": [
{
"question": "Which option do yo prefer?",
"id": "7f073efd-6f3d-43f2-9fe4-5cad683b77a2",
"votingOptions": [
{
"optionText": "Option 3",
"id": "3bc0a618-8791-4862-a7fd-5f2df464697d"
},
{
"optionText": "Option 1",
"id": "84c6a830-814b-40c8-a252-c074be5d689a"
},
{
"optionText": "Option 2",
"id": "8872ef6f-fc70-445a-802e-d39944006467"
}
]
}
]
}

VotingOption 中的映射函数永远不会被调用。

最佳答案

旧的 ListTransform 解决方案在 Swift 3 中不再有效。

这就是我现在使用的;把它放在一个名为 ListExtensions.swift 的文件中,例如。

import Foundation
import ObjectMapper
import RealmSwift

/// Maps object of Realm's List type
func <- <T: Mappable>(left: List<T>, 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)
}
}
}

这使您可以像这样简单地使用它:

class Parent: Object, Mappable {
dynamic var id: Int = 0
var children = List<Child>()

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

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

关于swift - Alamofire,对象映射器, Realm : Nested Objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33804181/

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