gpt4 book ai didi

ios - 如何在 Swift 中将字典数组存储到 Realm 数据库

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

我正在通过 swift 应用程序中的 api 调用从服务器获取 JSON 数据。因此,我想将其存储到 Realm 数据库中,并再次需要获取以在 TableView 中显示。

我对 Realm 数据库一无所知,在检查了几个论坛之后,我得到了创建对象类的基本想法。

所以,我已经安装了 Realm pod 文件并将该库导入到我的类中。

我的 JSON 数据是

[{
"type": "story",
"story": 

{
"author-name": "",
"headline": "Quotes ",
"summary": "Best quotes of Muhammad Ali",
"hero-image": "https://image”
}
},
{
"type": “Trending”,
"story": 
{
"author-name": "",
"headline": "Quotes ",
"summary": "Best quotes of Muhammad Ali",
"hero-image": "https://image”
}
},
{
"type": “Technology”,
"story": 

{
"author-name": "",
"headline": "Quotes ",
"summary": "Best quotes of Muhammad Ali",
"hero-image": "https://image”
}
},
{
"type": “Top”,
"story": 

{
"author-name": "",
"headline": "Quotes ",
"summary": "Best quotes of Muhammad Ali",
"hero-image": "https://image”
}
}
]

每个 type 关键字都有不同的模型类保存来自 api 数据的数据,以便在 Tableview 中显示

喜欢

let storyObj = StoryModule()
let trending = StoryModule()
let technology = StoryModule()
let stotopryObj1 = StoryModule()

我正在保存每个类型的每个键值

if abc.type == "story" {
let storyObj = abc.story
storyObj.authorname = storyObj?.authorname
storyObj.heroimage = storyObj?.heroimage
storyObj.headline = storyObj?.headline
storyObj.summary = storyObj?.summary
self.treningStoriesList.append(storyObj)
}

对于其余的“趋势”、“热门”和“技术”对象也是如此。

Realm 模块是

import RealmSwift

class DemoInfo: Object {
@objc dynamic var category = ""
let items = List<DemoList>()
}

class DemoList : Object {
@objc dynamic var authorName = ""
@objc dynamic var imageUrl = ""
@objc dynamic var summary = ""
@objc dynamic var headLine = ""
}

MainViewController类中,

let realmDB = try! Realm()

但是,在这里我感到震惊,如何保存这些 storyObj、technology、top 等 模块数据并获取。

有人可以推荐我吗?

最佳答案

如果要在数据库中添加 Realm 对象,则必须为每个 Realm 对象类定义主键。因此,在您可以像这样创建 Realm 对象之后,您需要更改 JSON 文件;

DemoObject.swift

import RealmSwift

class DemoObject: Object {

@objc dynamic var id: String = ""
@objc dynamic var type: String = ""
@objc dynamic var subObject: SubObject?

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

子对象.swift

import RealmSwift

class SubObject: Object {

@objc dynamic var id: String = ""
@objc dynamic var authorName: String = ""
@objc dynamic var imageUrl: String = ""
@objc dynamic var summary: String = ""
@objc dynamic var headLine: String = ""

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

然后,您可以使用这些代码来添加您的数据库。

let realm = try! Realm()

let demo = DemoObject()
demo.id = "1"

let sub = SubObject()
sub.id = "1"
sub.authorName = "Author Name"
sub.headLine = "Head Line"
sub.summary = "image Url"

demo.subObject = sub

try! realm.write {
realm.add(demo, update: true)
}

关于ios - 如何在 Swift 中将字典数组存储到 Realm 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52735851/

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