如何使用RealmSwift存储字典? [英] How can I store a Dictionary with RealmSwift?

查看:313
本文介绍了如何使用RealmSwift存储字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下模型:

class Person: Object {
    dynamic var name = ""
    let hobbies = Dictionary<String, String>()
}

我正在尝试在Realm中存储我从Alamofire请求中获得的类型为[String:String]的对象,但是由于hobbies 必须要通过let进行定义,因此无法到RealmSwift文档,因为它是List<T>/Dictionary<T,U>类型.

I'm trying to stock in Realm an object of type [String:String] that I got from an Alamofire request but can't since hobbies has to to be defined through let according to RealmSwift Documentation since it is a List<T>/Dictionary<T,U> kind of type.

let hobbiesToStore: [String:String]
// populate hobbiestoStore
let person = Person()
person.hobbies = hobbiesToStore

我也试图重新定义init(),但总是以致命错误告终.

I also tried to redefine init() but always ended up with a fatal error or else.

如何在RealSwift中简单地复制或初始化字典? 我在这里错过了一些琐碎的事情吗?

How can I simply copy or initialize a Dictionary in RealSwift? Am I missing something trivial here?

推荐答案

Dictionary作为Realm中的属性类型不受支持. 您需要引入一个新类,该类的对象描述每个键-值对和一对多关系,如下所示:

Dictionary is not supported as property type in Realm. You'd need to introduce a new class, whose objects describe each a key-value-pair and to-many relationship to that as seen below:

class Person: Object {
    dynamic var name = ""
    let hobbies = List<Hobby>()
}

class Hobby: Object {
    dynamic var name = ""
    dynamic var descriptionText = ""
}

对于反序列化,您需要将JSON中的字典结构映射到Hobby对象,并将键和值分配给适当的属性.

For deserialization, you'd need to map your dictionary structure in your JSON to Hobby objects and assign the key and value to the appropriate property.

这篇关于如何使用RealmSwift存储字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆